2015-01-21 126 views
0

運行下面的代碼:爲什麼過程返回-1?

int main() 
{ 
    double hour[3]; 
    double charge[3]; 

    double sum_hour = 0; 
    double sum_charge = 0; 

    for (int i = 1; i <= 3; i++) 
    { 
     cout<<"Enter the hours for car No. "<<i<<": "; 
     cin>>hour [i]; 

     if (hour [i] <= 3.0) 
      {charge [i] = 2.00;} 
     if (hour [i] > 3.0 && hour [i] < 24) 
      {charge [i] = 2.00 + (ceil(charge [i] -3))*0.5;} 
     if (hour [i] == 24.0) 
      {charge [i] = 10.00;} 

     sum_hour = sum_hour + hour [i]; 
     sum_charge = sum_charge + charge [i]; 
    } 

    cout<<"Car"<<setw(10)<<"Hours"<<setw(10)<<"Charge"<<endl; 


} 

我收到以下消息for循環後已執行和循環之後的代碼不運行COUT

Process returned -1 (0xFFFFFFFF) execution time... 

回答

3

在循環中for (int i = 1; i <= 3; i++)數組索引應從0開始。你的循環更改爲:

for (int i = 0; i < 3; i++) 

你的數組索引超出界限時i is 3這裏cin>>hour [i];,其不確定的行爲。

要添加在這裏,不要做浮點比較:

if (hour [i] <= 3.0)// 

雖然這是不相關的你原來的問題,請閱讀Why doesn't my floating-point comparison work?