0

プログラムにコマンド ライン引数を追加しようとしています。だから私は実験していましたが、私の人生に対するこのインテリセンスの警告を理解することはできません. 「)」が必要だと言い続けますが、その理由はわかりません。

気に入らないコードは次のとおりです。

    // 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;

}

4

2 に答える 2

9

マイナス記号と思われる文字は別のものであるため、減算演算子として解析されません。

あなたのバージョン:

average = sum / ( argc – 1 ); 

正しいバージョン (コピーしてコードに貼り付けます):

average = sum / ( argc - 1 ); 

整数を使用して平均を計算することは、最適な方法ではない可能性があることに注意してください。floatRHS に整数演算があり、それをLHSに割り当てます。浮動小数点型を使用して除算を実行する必要があります。例:

#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
}
于 2013-02-17T20:50:50.277 に答える
2

私のマシンで g++ 4.6.3 を使用してコードをコンパイルしようとしましたが、次のエラーが発生しました。

pedro@RovesTwo:~$ 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

その行に奇妙な文字があるようです。行を削除して書き直して、エラーを修正しました。

于 2013-02-17T20:58:44.823 に答える