求解,不知道哪里有错误
代码如下:#include<stdio.h>
int main()
{
printf("请依次输入整数成绩(输入stop停止):");
float ave;
int times,total;
char scores;
times = 0;
total = 0;
while(scores == 'stop')
{
scanf("%d",&scores);
total += scores;
times+=1;
printf("%d\n",total);
}
ave = (float)total/times;
printf("%.2f",ave);
}
我的想法是每次输入一个分数,然后打印出平均值,输入'stop'就结束输入,打印出平均值,但是尝试了好几次都不行
改成输入0结束代码如下:
#include<stdio.h>
int main()
{
printf("请依次输入整数成绩(输入0停止):");
float ave;
int times,total,scores;
times = 0;
total = 0;
do
{
scanf("%d",&scores);
total = total + scores;
times++;
}while(scores != 0);
ave = (float)total/(times - 1);
printf("%.2f",ave);
}
如果我想改成输入'stop',结束输入的话该怎么改,求助!!! 本帖最后由 jackz007 于 2022-9-24 14:21 编辑
#include <stdio.h>
#include <string.h>
int main(void)
{
int times , total , scores ;
char s ;
float ave ;
printf("请依次输入整数成绩(输入stop停止):") ;
for(total = times = 0 ;;) {
gets(s) ;
if(strncmp(s , "stop" , 4)) {
sscanf(s , "%d" , & scores) ;
total += scores ;
times += 1 ;
printf("%d\n" , total) ;
} else {
break ;
}
}
ave = (float) total / times ;
printf("the average score = %.2f\n" , ave) ;
}
编译、运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
请依次输入整数成绩(输入stop停止):100
100
98
198
95
293
96
389
92
481
stop
the average score = 96.20
D:\\C> jackz007 发表于 2022-9-24 14:18
编译、运行实况:
感谢!虽然还有一些看不懂的代码哈哈哈哈哈{:5_109:} 灯火阑珊201 发表于 2022-9-24 14:26
感谢!虽然还有一些看不懂的代码哈哈哈哈哈
主要是输入字符串 scanf() 不可以用 "%d" 的格式描述符。 问题在于:根据数据类型要求,%d读入的是数字,你要求在读入stop的时候停止,数据类型不符合。应该会出错。读入单个字符是用%c,读入字符串是用%s。
页:
[1]