试图从数组

时间:2016-09-16 01:27:33

标签: c++ arrays infinite-loop

我试图显示数组中的所有数字,但每行只显示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;
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您有未定义的行为。

1.Quit your Xcode 2.Restart your system 3.Go to ~/Library/Developer/Xcode/DerivedData and Delete this folder 4.Clean your project 5.Run 介于20和100之间。

您在分配number时将其用作大小。

然后运行一个循环范围[0,1000],它使用array来索引超过该数组末尾的路径。

答案 2 :(得分:0)

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

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="504" height="504" viewBox="0 0 504 504">
  <g class="group">
    <path d="M415.8 134.3c0 0 70 59.2 16.7 211.7 0 0-34.2 108.7-123.3 133.3 0 0-18.3 9.2-44.2-4.2 0 0-15.8-14.2-56.7-0.8 0 0-22.5 8.3-50.8-13.3 0 0-125.8-102.5-136.7-215.8 0 0-14.2-92.5 85-128.3 0 0 60.8-19.2 109.2 15.8 0 0-15-57.5-38.3-90.8 0 0 25.8-21.7 38.3-1.7 0 0 15.8 20.8 30.8 94.2 0 0 3.3-2.5 25-11.7 0 0 80.8-77.5 204.2-61.7C475 61 467.5 101 415.8 134.3z"
    />
    <path fill="#006600" d="M247 157c0 0 73.3-96 218.7-90 0 0-18 54-85.3 77.3 0 0-58.7 26-132.7 20L247 157z" />
    <path fill="#660000" d="M188.3 43c0 0 14-12.7 22 2.7 0 0 40 74.7 26 144 0 0-10 4.7-6-21.3 0 0 4.7-8-10.7-48C219.7 120.3 198.3 58.3 188.3 43z" />
    <path fill="#990000" d="M247 171.7c0 0 89.3 11.3 162.7-34 0 0 52.7 51.3 31.3 152 0 0-20 128-109.3 173.3 0 0-32.7 17.3-50 8 0 0-30-18.7-75.3-4 0 0-25.3 6.7-38.7-8.7 0 0-104.7-89.3-132.7-180 0 0-32-88 45.3-142 0 0 65.3-42.7 140.7 7.3 0 0 4.7 16.7 2 32 0 0-1.3 29.3 16.7 18.7C239.7 194.3 247 186.3 247 171.7z"
    />
  </g>
</svg>

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