【发布时间】:2015-03-24 14:18:18
【问题描述】:
对于我的第一个任务,我使用fgets() 从stdin 读取字符串。所以我在终端上输入1234567890 并将字符串存储到一个名为str 的变量中。现在我想拆分数字并执行加法。在这种情况下,总和将是 55,因为 1+2+3+4+5+6+7+8+9+0 = 55。
我该怎么做?
到目前为止我的代码
#include <stdio.h>
#include <string.h>
int main(void){
char str[100];
printf("Please enter the 10 digit number \n");
fgets(str, 10, stdin);
//Separate the digits
//calculate their sum
int sum =..............
//print out the sum
printf("the sum of the digits is: %s", sum);
return(0);
}
【问题讨论】:
-
初始化一个 'sum' 变量为 0。迭代字符串直到结束。将每个 ASCII 字符转换为 int。将其添加到“总和”变量中。