【发布时间】: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;
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
另外,你应该explain your code, line by line, to your rubber duck。我敢打赌,你的橡皮鸭知道你的代码为什么不起作用。
标签: c++ arrays infinite-loop