argc和argv的问题
试图将命令行参数添加到我的程序中。所以我正在做实验,并且无法弄清楚我对这个生活的这种智能警告。它一直说它期待着')',但我不知道为什么。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;
}
你认为该字符是一个减号是别的东西,所以它不会被解析为一个减法运算符。
您的版本:
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
}
Hä?解释说,更多请... – 2013-02-17 20:52:48
@ G-makulik:他在他的节目一个奇怪的非ASCII Unicode字符,看起来像一个减号,而不是 – 2013-02-17 20:53:29
OK,我可以**现在看到**点.. 。 – 2013-02-17 20:54:00
我试图使用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
看起来有在该行一些奇怪的字符。删除并重新写入该行修复错误。
有点晚了,这恰恰反映了什么@ juanchopanza的回答预测... – 2013-02-17 21:00:38
嗯,是的+1尝试... – 2013-02-17 21:10:47
它可能会试图警告你,你可能期待着什么,从你计算什么不同。提示:“sum”和“argc”的类型是什么? :-) – 2013-02-17 20:49:39