正在尝试向我的程序添加命令行参数。因此,我一直在试验,但终生无法弄明白这个智能感知警告。它一直在说它期待一个')',但我不知道为什么。
下面是它不喜欢的代码:
// 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;}
发布于 2013-02-18 04:50:50
您认为是减号的字符是其他字符,因此它不会被解析为减法运算符。
您的版本:
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
}发布于 2013-02-18 04:58:45
我尝试用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看起来该行中有一些奇怪的字符。删除并重写该行已修复错误。
https://stackoverflow.com/questions/14925894
复制相似问题