C++ 试图从数组中每行显示10个数字
我试图显示数组中的所有数字,但每行仅显示10个。当我运行我的代码时,我在一个无限循环中得到“168”。如果能帮上点忙,那就太好了。我真的被卡住了。如果C++不明显,则非常新。p>C++ 试图从数组中每行显示10个数字,c++,arrays,infinite-loop,C++,Arrays,Infinite Loop,我试图显示数组中的所有数字,但每行仅显示10个。当我运行我的代码时,我在一个无限循环中得到“168”。如果能帮上点忙,那就太好了。我真的被卡住了。如果C++不明显,则非常新。p> #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int number = 0; int count = 0; float average = 0;
#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
整数=0;
整数计数=0;
浮动平均值=0;
int最大=-1;
最小整数=-1;
int*数组;
数量;
如果(number>=20&&number仔细查看此循环:用于(int i=0;i<1000;)
它缺少哪个部分?您有未定义的行为
编号
介于20和100之间(含20和100)
分配数组时,将其用作大小
然后运行一个循环范围[01000],它使用i
索引该数组的末尾。由于以下行,您将运行一个无限循环:
for (int i = 0; i < 1000;)
for(int i=0;i<1000;)
这缺少增量表达式,因此条件表达式(i<1000)
始终(也称为无限)保持为真。解决此类问题的正确工具是调试器。在询问堆栈溢出之前,您应该逐行检查代码。有关更多帮助,请阅读。至少,您应该[编辑]您的问题需要包括一个重现您的问题的示例,以及您在调试器中所做的观察。此外,您应该。我打赌100个四分之一的数字,您的橡皮鸭知道您的代码不工作的原因。不,但这只是因为该循环从不递增。另一方面,您的变量k
在这里似乎是多余的,并且重复了<代码>索引< /代码>变量。您可能需要考虑使用<代码>索引>代码>变量本身,并去掉<代码> k>代码>以保持代码简洁明了。