依次输入一个学生的学号,以及3科(C语言,数学,英语)成绩,在屏幕上输出该学生的学号,3科成绩(注:输出成绩时需进行四舍五入且保留2位小数)。
数据范围:学号满足
,各科成绩使用百分制,且不可能出现负数
学号以及3科成绩,学号和成绩之间用英文分号隔开,成绩之间用英文逗号隔开。
学号,3科成绩,输出格式详见输出样例。
17140216;80.845,90.55,100.00
The each subject score of No. 17140216 is 80.85, 90.55, 100.00.
123456;93.33,99.99,81.20
The each subject score of No. 123456 is 93.33, 99.99, 81.20.
#include <stdio.h> int main() { int id; double score1, score2, score3; scanf("%d;%lf,%lf,%lf", &id, &score1, &score2, &score3); // 添加0.0005偏移确保四舍五入正确 printf("The each subject score of No. %d is %.2f, %.2f, %.2f.", id, score1 + 0.0005, score2 + 0.0005, score3 + 0.0005); return 0; }float类型用不了,四舍五入的精度不够,让人很费解
我这个一直报错是什么原因 #include <stdio.h> double a, b, c; unsigned int xuehao; int main() { scanf("%d;%lf,%lf,%lf", &xuehao, &a, &b, &c);//scanf可以实现一次获取多个不同类型的按键值 printf("The each subject score of No. %d is %.2lf, %.2lf, %.2lf.", xuehao, a, b, c); return 0; }
这样子可以通过,我猜大概率是浮点数存储有误差,导致有时候没法很好做到四舍五入。我这里定义了一个函数可以稍微纠正一下;#include <stdio.h>float sheru(float q){int x=0;x=(int)(q*1000)%10;if(x>4) q=q+0.01-x*0.001;else q=q-x*0.001;return q;}int main() {long number=0;float c=0,m=0,e=0;scanf("%ld;%f,%f,%f",&number,&c,&m,&e);c=sheru(c);m=sheru(m);e=sheru(e);printf("The each subject score of No. %ld is %.2f, %.2f, %.2f.",number,c,m,e);return 0;}
#include <math.h> #include <stdio.h> int main() { int SuID = 0; float C = 0; float math = 0; float Eg = 0; scanf("%d;%f,%f,%f",&SuID,&C,&math,&Eg); printf("The each subject score of No. %d is %.2f, %.2f, %.2f.",SuID,round(C * 100) / 100,math,Eg); return 0; } //C语言成绩这里因为浮点数存储有不准确性,所以有概率出现四舍五入不对的情况,这个时候要用round(变量 * 100) / 100 来让浮点数变得具有准确性
#include <stdio.h> int main() { int n = 0; float C = 0.0; float M = 0.0; float Y = 0.0; scanf("%d;%f,%f,%f",&n,&C,&M,&Y); printf("The each subject score of No. %d is %.2f, %.2f, %.2f.",n,C,M,Y); return 0; }