【问题标题】:Trying to display 10 numbers per line from array尝试从数组中每行显示 10 个数字
【发布时间】:2016-09-16 01:27:33
【问题描述】:

我正在尝试显示数组中的所有数字,但每行仅显示 10 个。当我运行我的代码时,我在无限循环中得到“168”。一些帮助会很棒我真的被困住了。如果不是很明显的话,它对 C++ 来说是非常新的。

#include <iostream>
#include <cstdlib> 
#include <ctime>
using namespace std;

int main()
{
int number = 0;
int count = 0;
float average = 0;
int largest = -1;
int smallest = -1;
int *array;


cout << "Please enter a number between 20 and 100: ";
cin >> number;

if (number >= 20 && number <= 100)
{
    int k = 0;
    array = new int[number];
    srand((unsigned)time(0));
    int random;
    for (int index = 0; index < number; index++)
    {
        random = (rand() % 1000) + 1;
        array[k] = random; k++;
    }
    for (int i = 0; i < 1000;)
    {
        cout << array[i] << "";
        if ((i + 1) % 10 == 0)
        {
            cout << endl;
        }
    }
}
else
{
    cout << "The number must be between 20 and 100. \n";
    cout << "Please enter a number between 20 and 100: " << endl;
    cin >> number;
}
system("Pause");
return 0;
}

【问题讨论】:

标签: c++ arrays infinite-loop


【解决方案1】:

仔细看看这个循环:for (int i = 0; i &lt; 1000;)它缺少哪一部分?

【讨论】:

    【解决方案2】:

    你有未定义的行为。

    number 介于 20 和 100 之间,包括 20 和 100。

    你在分配array时使用它作为大小。

    然后您运行一个循环范围 [0,1000),它使用 i 来索引超出该数组末尾的方式。

    【讨论】:

    • 不,只是因为那个循环永远不会增加。
    【解决方案3】:

    由于以下行,您遇到了无限循环:

    for (int i = 0; i < 1000;)
    

    这缺少增量表达式,因此条件表达式 (i &lt; 1000) 始终(a.k.a 无限)保持为真。

    【讨论】:

    • 附带说明:您的变量k 似乎是多余的,并且重复了index 变量。您可能需要考虑使用 index 变量本身,并去掉 k 以保持您的代码简洁明了。
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多