[英]Change the way my output is displayed in C program?
Sorry for bad topic name, i couldn't think of any. 对不起主题名称不好,我想不出来。 I have created this program that gets 7 values, add them and prints average, at the end it prints all the entered values in this format:
我创建了这个程序,它获取7个值,添加它们并打印平均值,最后它以这种格式打印所有输入的值:
10, 15, 20, 15, 30, 45, 50,
I want it to display a comma after every value but after the last value I want to display dot like this: 我希望它在每个值后显示一个逗号但在最后一个值之后我想要显示这样的点:
10, 15, 20, 15, 30, 45, 50.
My code: 我的代码:
float sumFunk(float a, float b) {
return ( (float) a + b);
}
float avgFunk(float a, float b) {
return (a / b);
}
int main(void) {
float avg = 0;
float cWeek[7] = {0};
int counter, sum = 0;
for ( counter = 0; counter <= 6; counter++) {
printf("Enter Temperature of day %d: ", counter+1); scanf("%f", &cWeek[counter]);
sum = sumFunk(sum, cWeek[counter]);
}
avg = avgFunk(sum, counter);
printf("Average Temp of %d days: %.2f \n", counter, avg);
for ( counter = 0; counter <= 5; counter++ ) {
printf("%.2f, ", cWeek[counter]);
}
}
The typical way to accomplish this task is with code like this 完成此任务的典型方法是使用这样的代码
for ( counter = 0; counter < 7; counter++ )
printf("%.2f%s", cWeek[counter], (counter + 1 == 7) ? ".\n" : ", " );
counter + 1 == 7
checks to see if the loop is about to end. counter + 1 == 7
检查循环是否即将结束。 If so, the string .\\n
is appended to the output, otherwise a comma and space are appended. 如果是,则将字符串
.\\n
附加到输出,否则将附加逗号和空格。
after the following printf line: 在以下printf行之后:
printf("Average Temp of %d days: %.2f \n", counter, avg);
add this line: 添加此行:
int last_element = cWeek [ sizeof cWeek ];
and then at the end add this if loop: 然后在最后添加这个if循环:
if ( last_element == '\0' ) { //whenever a list ends, this '\0' end character is added as well.
printf("%.2f. ", cWeek[counter]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.