简体   繁体   English

总结命令行

[英]Summing the command line

Pretty straightforward, I am trying to sum all of the integers input in the command line. 非常简单,我试图将命令行中输入的所有整数相加。 The sum actually works, if I start the program with " 1 1 1 1 " input, the sum increments by one four times. 该和实际上有效,如果我使用“ 1 1 1 1”输入启动程序,该和将增加四倍。 The problem is that sum is initialized at some really large number (4293283588). 问题在于总和被初始化为一个非常大的数字(4293283588)。 Why is that? 这是为什么?

int main(int argc, char*argv[])
{
  int a = 0;
  int sum = 0;
  size_t i = 0;

  for (i=0; i<argc; i++)
  {
     a = atoi(argv[i]);
     sum = sum + a;
     printf("%ld\n", sum);
  }

  return 0;
}

argv[0] is perhaps the name of the executable. argv[0]可能是可执行文件的名称。 From the standard: 从标准:

5.1.2.2.1 Program startup 5.1.2.2.1程序启动

.... ....

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name ; 如果argc的值大于零,则argv[0]指向的字符串表示程序名称 argv[0][0] shall be the null character if the program name is not available from the host environment. 如果程序名称在主机环境中不可用,则argv[0][0]应为空字符。 If the value of argc is greater than one, the strings pointed to by argv[1] 如果argc的值大于1,则argv[1]指向的字符串
through argv[argc-1] represent the program parameters . argv[argc-1]表示程序参数

Try 尝试

for (i=1; i<argc; i++)

Also, as @BLUEPIXY indicated, %ld assumes type long . 同样,如@BLUEPIXY所示, %ld假定为long类型。 So either change it to %d , or use long sum . 因此,要么将其更改为%d ,要么使用long sum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM