如果要重复整个输入和平均过程,可以在代码周围循环:
#include <stdio.h>
int main(void)
{
float f1,f2,f3;
while (1)
{
printf("Please enter three numbers.\n");
printf("\tFirst number please.\n");
if (scanf("%f", &f1) != 1)
break;
printf("\tSecond number please.\n");
if (scanf("%f", &f2) != 1)
break;
printf("\tThird number please.\n");
if (scanf("%f", &f3) != 1)
break;
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
请注意,此代码在scanf()
每次使用时都会检查返回值,如果出现问题则中断循环。不需要字符串连接,一个单一的printf()
当然可以打印一个字符串和一个值。
这是一个简单的第一阶段;可以使用更精细的技术。例如,您可以创建一个函数来提示和读取数字:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
如果您想摆脱一组固定的三个值,那么您可以迭代直到遇到 EOF 或错误:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float value;
float sum = 0.0;
int num = 0;
printf("Please enter numbers.\n");
while (prompt_and_read("\tNext number please.\n", &value) == 0)
{
sum += value;
num++;
}
if (num > 0)
{
printf("You entered %d numbers\n", num);
printf("Your sum is %f\n", sum);
printf("Your average is %f\n", sum / num);
}
return 0;
}
您可能还决定将提示字符串末尾的换行符替换为空格,以便在与提示相同的行上键入值。
如果要检查是否重复计算,可以在代码的第一个或第二个版本上使用一个次要变体:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
static int prompt_continue(const char *prompt)
{
printf("%s", prompt);
char answer[2];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n') // Gobble to newline
;
return 1;
}
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
if (prompt_continue("Do you want to try again?") == 0)
break;
}
return 0;
}