【发布时间】:2019-09-20 21:36:28
【问题描述】:
我需要在单个文件“sum.c”中编写一个程序,该文件在命令行上接受多个整数,获取这些整数的总和并将它们打印到标准输出。程序必须使用 strtol 之类的东西从字符串转换为数字。
到目前为止,我的代码如下所示:
#include <stdio.h>
int main (int argc, char *argv[]){
int a, b, sum;
int i; //looping through arguments using i
if (argc<2) {
printf("Please include at least two integers to get the sum.\n");
return -1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
sum=a+b;
printf(sum);
return (0);
}
这包括一个错误检查,以确保至少传递了两个参数。但是我当前的代码只允许两个参数。我需要弄清楚如何更改它以处理任意数量的参数,并检查传递的数字是否仅为整数而没有别的。我在此处发布的原始代码仍然存在编译错误。我从编码中休息了很长时间,所以我知道目前它很差。
更新代码:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int sum;
sum = 0;
if (argc<2) {
printf("Please include at least two integers to get the
sum.\n");
exit (-1);
}
for (int counter = 1; argv[counter] != NULL; ++counter) {
sum += atoi(argv[counter]);
}
printf("%d\n", sum);
exit (0);
}
现在看起来怎么样?
执行时收到错误:
./sum.c: line 4: syntax error near unexpected token `('
./sum.c: line 4: `int main (int argc, char *argv[]) {'
【问题讨论】:
-
使用
for循环遍历所有参数。 -
printf(sum)应该是printf("%d\n", sum); -
我根据您的建议更新了代码。现在看起来怎么样?
-
你仍然需要在最后修复
printf()。循环看起来不错,尽管您没有验证参数实际上是一个数字。 -
哦,抱歉,我在我的代码中更新了它,但忘记在此处添加它。是的,我认为为了验证参数,我需要运行 if 语句来检查参数是否为整数?此外,当我运行此代码时,我收到第 4 行错误。