更改我的输出在C程序中的显示方式?

时间:2014-03-29 03:59:18

标签: c

抱歉主题名称不好,我无法想到。我创建了这个程序,它获得7个值,添加它们并打印平均值,最后它以这种格式打印所有输入的值:

10, 15, 20, 15, 30, 45, 50,

我希望它在每个值后显示一个逗号但在最后一个值之后我想要显示这样的点:

10, 15, 20, 15, 30, 45, 50.

我的代码:

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]);
    }
}

2 个答案:

答案 0 :(得分:2)

完成此任务的典型方法是使用此代码

for ( counter = 0; counter < 7; counter++ )
    printf("%.2f%s", cWeek[counter], (counter + 1 == 7) ? ".\n" : ", " );

counter + 1 == 7检查循环是否即将结束。如果是,则将字符串.\n附加到输出,否则将附加逗号和空格。

答案 1 :(得分:-1)

在以下printf行之后:

printf("Average Temp of %d days: %.2f \n", counter, avg);

添加以下行:

int last_element = cWeek [ sizeof cWeek ];

然后在最后添加这个if循环:

if ( last_element == '\0' ) { //whenever a list ends, this '\0' end character is added as well.

printf("%.2f. ", cWeek[counter]);

}