argc和argv出现故障

Trouble with argc and argv

本文关键字:故障 argv argc      更新时间:2023-10-16

我正在尝试将命令行参数添加到程序中。所以我一直在做实验,无法理解这种对我生命的智能感知警告。它一直说它在期待一个")",但我不知道为什么。

这是它不喜欢的代码:

// 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 the 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 an invalid number of arguments, display an error message
        // and usage syntax
        std::cout << "Error: No argumentsn"
                  << "Syntax: command_line [space-delimited 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在我的机器上编译你的代码,但得到了以下错误:

cd ~
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

看起来这行有一些奇怪的字符。删除并重新写入行修复了错误。