[英]Trouble with argc and 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;
}
您認為是減號的字符是其他字符,因此不會將其解析為減法運算符。
您的版本:
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
}
我嘗試使用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
看起來該行中有一些奇怪的字符。 刪除並重新寫入修正錯誤的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.