2017-09-26 193 views
0
#include <iostream> 
using namespace std; 

int main() 
{ 
    int nums[20] = { 0 }; 
    int a[10] = { 0 }; 

    cout << a << endl; 
    cout << nums << endl; 

    cout << "How many numbers? (max of 10)" << endl; 
    cin >> nums[0]; 
    for (int i = 0; i < nums[0]; i++) 
    { 
    cout << "Enter number " << i << endl; 
    cin >> a[i]; 
    } 
    // Output the numbers entered 
    for (int i = 0; i < 10; i++) 
     cout << a[i] << endl; 
    return 0; 
} 

如果這個程序運行,我們輸入255多少個數字,每個數字9個,它會導致它崩潰。這個C++程序爲什麼會導致系統崩潰?

+2

「它導致它崩潰」中的第二個「it」是什麼?整個電腦的操作系統,或只是你的程序? –

+0

如果您正在學習C++,首先需要了解標準庫中提供了哪些工具。當存儲類似數組的數據時,['std:vector'](http://en.cppreference.com/w/cpp/container/vector)是一個很好的開始。使用那些優先於固定長度的C風格的陣列,就像你在這裏一樣。 – tadman

回答

1

您正在使用nums[0]作爲循環的最大範圍

for (int i = 0; i < nums[0]; i++) 
    { 
    cout << "Enter number " << i << endl; 
    cin >> a[i]; 
    } 

就你而言,你正在做255個循環,並且在每次迭代中,將值添加到a[i]

您聲明數組a的大小爲10個元素,但您試圖添加255個元素。

這是問題。 a的大小需要與主循環的最大邊界值(nums[0])相同。

0

爲什麼你的程序崩潰?您只爲a分配了10個元素。


您告訴用戶"(max of 10)"。用戶忽略此並在255中鍵入。在做其他事情之前,您需要檢查用戶是否聽取了您的警告。

cout << "How many numbers? (max of 10)" << endl; 
cin >> nums[0]; 

// Has the user listened to your warning? 
if (nums[0] > 10) { 
    cout << "Bad input!" << endl; 
    return 0; 
} 
1

其因int a[10] = { 0 };並嘗試索引它過去的第10個小區或位置9 你需要修復您的for循環

for (int i = 0; i < nums[0]; i++) 
    { 
    cout << "Enter number " << i << endl; 
    cin >> a[i]; 
    } 

或更改intialization

你的電池的長度