总是编译不出结果
任务描述
编程输入至少一个整数(具体数量不限),输出它们的和。
有如下问题:
1.最后printf中的&符号要去掉,printf中打印变量值是不需要这个的
2.需要判断如何跳出循环输出结果,因为是换行出结果,所以我们判断输入的字符是否有换行
#include<stdio.h>
#include<string.h>
int main(){
int a = 0;
int sum = 0;
while(scanf("%d",&a) != EOF){
sum += a;
if(getchar() == '\n'){
break;
}
}
printf("%d\n",sum);
}
对您有帮助的话希望可以采纳
printf("%d",sum);
sum不需要加&符号
把第9行的&sum改为sum再试试,因为打印变量的值这里不需要加取址符。可以用gets读取一行输入后,再逐个从输入的这个字符串读取整数,然后计算他们的和即可,代码如下:
参考链接:
C 库函数 – gets() | 菜鸟教程
用c语言判断字符串为空,如何检查C字符串是否为空_咯嗯的博客-CSDN博客
使用atoi函数头文件,c语言编写atoi函数-天道酬勤-花开半夏
C语言中 字符串和数字的相互转换_菜鸟xiaowang的博客-CSDN博客_c字符串转化为数字
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main(void){
// int a;
char a[100]={'\0'}; //存储输入的一行字符串的字符数组
int sum=0;
//https://www.runoob.com/cprogramming/c-function-gets.html
gets(a); //读取一行字符串输入
//https://blog.csdn.net/weixin_35988038/article/details/117272214
int index=0;
//从输入的这行字符串提取所有的整数
while(a[index]!='\0'){
//https://www.zhangshilong.cn/work/289871.html
//https://blog.csdn.net/xiaowang_lj/article/details/125333628
char num[10]={'\0'}; //存储每个整数
int ti=0;
//从输入的字符串读取一个整数
for(int i=0;a[index]!=' '&&a[index]!='\0';index++,i++){
num[i] = a[index];
ti=i; //记录有字符串的长度,以便在每个数字字符串结尾添加空字符
}
num[ti+1]='\0';
sum+=atoi(num); //把每个整数转换为数字,并把他累加到和中
//printf("num=%s,sum=%d,index=%d,a[%d]=%d\n",num,sum,index,index,a[index]);
// getchar();
if(a[index]==' '){ //如果当前字符为空格,则指向下一个字符
index++;
}
}
//打印结果
printf("%d",sum);
return 0;
}