【问题标题】:No output from cout when calling void function调用 void 函数时 cout 没有输出
【发布时间】:2015-02-16 21:05:36
【问题描述】:

我是 C++ 新手,请耐心等待。

我正在尝试根据某些参数(间隔大小、包含数字数量的数组长度、最高数字 yadayada)创建直方图。

虽然我认为我的函数中有正确的公式,但细节无关紧要,而且是我自己要摆弄的问题。

当我从 C++ IO“cin”分配变量时,我可以通过“cout”调用输出这些变量,但是,当我调用还包含“cout”指令的直方图函数时,不会打印任何内容。

我的代码:

#include <iostream>
#include <cmath>

using namespace std;

void histogram(int l, int n, int k, int *a)
{
        int quantity = 0;
        for (int i = 1; i <= l; i++)
        {
                for (int j = 0; i < n; j++)
                {
                        if (a[j] >= (i-1) * k || a[j] <= i * k)
                        {
                                quantity++;
                        }
                }

                cout << (i-1) * k + ": " + quantity << endl;
                quantity = 0;
        }
}


int main()
{
        int l,n,k;
        int *a;

        a = new int[n];

        cin >> l >> n;

        for (int i = 0; i < n; i++)
        {
                cin >> a[i];
        }

        k = ceil((double)a[0]/l);

//      cout << k;

        histogram(l,n,k,a);

        return 0;
}

【问题讨论】:

  • 在为n 设置值之前调用a = new int[n];。这会导致未定义的行为。 cin &gt;&gt; l &gt;&gt; n 也不会导致时间旅行。
  • 什么是l(应该是什么,实际上是什么)?直方图中的循环可能永远不会运行,并且由于 cout 在该循环内,因此可能永远无法到达 cout
  • 使用调试器单步调试代码
  • cout &lt;&lt; (i-1) * k + ": " + quantity &lt;&lt; endl; 字符串连接不起作用,使用cout &lt;&lt; (i-1) * k &lt;&lt; ": " &lt;&lt; quantity &lt;&lt; endl;
  • @MattMcNabb 老兄,他真棒

标签: c++


【解决方案1】:

这条线和字符串的连接可能会发生一些奇怪的事情: cout &lt;&lt; (i-1) * k + ": " + quantity &lt;&lt; endl; 您可以尝试重写为 cout &lt;&lt; ((i-1) * k) &lt;&lt; ": " &lt;&lt; quantity &lt;&lt; endl;,以确保正确添加和连接。

【讨论】:

  • 是的,int + char* + int 将通过两个整数值偏移到 char* 中。最有可能达到 char 0 的填充。因此不打印任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多