2013-02-17 90 views
0

試圖將命令行參數添加到我的程序中。所以我正在做實驗,並且無法弄清楚我對這個生活的這種智能警告。它一直說它期待着')',但我不知道爲什麼。argc和argv的問題

這裏是它不喜歡的代碼:

// Calculate average 
    average = sum/(argc – 1); 

然後,它強調的減法運算符。以下是完整的程序。

#include <iostream> 

int main(int argc, char *argv[]) 
{ 
    float average; 
    int sum = 0; 

    // Valid number of arguments? 
    if (argc > 1) 
    { 
     // Loop through arguments ignoring the first which is 
     // the name and path of this program 
     for (int i = 1; i < argc; i++) 
     { 
      // Convert cString to int 
      sum += atoi(argv[i]);  
     } 

     // Calculate average 
     average = sum/(argc – 1);  
     std::cout << "\nSum: " << sum << '\n' 
       << "Average: " << average << std::endl; 
    } 
    else 
    { 
    // If invalid number of arguments, display error message 
     // and usage syntax 
     std::cout << "Error: No arguments\n" 
     << "Syntax: command_line [space delimted numbers]" 
     << std::endl; 
    } 

return 0; 

}

+2

它可能會試圖警告你,你可能期待着什麼,從你計算什麼不同。提示:「sum」和「argc」的類型是什麼? :-) – 2013-02-17 20:49:39

回答

9

你認爲該字符是一個減號是別的東西,所以它不會被解析爲一個減法運算符。

您的版本:

average = sum/(argc – 1); 

正確的版本(剪切並粘貼到您的代碼):

average = sum/(argc - 1); 

注意,計算使用整數平均可能無法做到這一點的最好辦法。你在RHS上有整數運算,然後你在LHS上分配給float。您應該使用浮點類型執行除法。例如:

#include <iostream> 

int main() 
{ 
    std::cout << float((3)/5) << "\n"; // int division to FP: prints 0! 
    std::cout << float(3)/5 << "\n"; // FP division: prints 0.6 
} 
+0

Hä?解釋說,更多請... – 2013-02-17 20:52:48

+2

@ G-makulik:他在他的節目一個奇怪的非ASCII Unicode字符,看起來像一個減號,而不是 – 2013-02-17 20:53:29

+0

OK,我可以**現在看到**點.. 。 – 2013-02-17 20:54:00

2

我試圖使用g ++ 4.6.3編譯我的機器上的代碼,並得到了如下錯誤:

[email protected]:~$ g++ teste.cpp -o teste 
teste.cpp:20:8: erro: stray ‘\342’ in program 
teste.cpp:20:8: erro: stray ‘\200’ in program 
teste.cpp:20:8: erro: stray ‘\223’ in program 
teste.cpp: Na função ‘int main(int, char**)’: 
teste.cpp:16:33: erro: ‘atoi’ was not declared in this scope 
teste.cpp:20:35: erro: expected ‘)’ before numeric constant 

看起來有在該行一些奇怪的字符。刪除並重新寫入該行修復錯誤。

+0

有點晚了,這恰恰反映了什麼@ juanchopanza的回答預測... – 2013-02-17 21:00:38

+0

嗯,是的+1嘗試... – 2013-02-17 21:10:47