优化以下C程序使其更简洁:#include stdioh#include ctypehchar get_choicevoid;char get_firstvoid;int mainvoid int choice; char ch; float num1 num2; while choice = get_choice != q printfEnter first number; while s
#include <stdio.h> #include <ctype.h>
char get_choice(void); float get_num(void); char get_first(void);
int main(void) { int choice; float num1, num2;
while ((choice = get_choice()) != 'q') {
printf("Enter first number: ");
num1 = get_num();
printf("Enter second number: ");
num2 = get_num();
switch (choice) {
case 'a':
printf("%f\n", num1 + num2);
break;
case 's':
printf("%f\n", num1 - num2);
break;
case 'm':
printf("%f\n", num1 * num2);
break;
case 'd':
while (num2 == 0) {
printf("Enter a number other than 0: ");
num2 = get_num();
}
printf("%f\n", num1 / num2);
break;
default:
printf("Please respond with a, s, m,d, or q.\n");
break;
}
}
return 0;
}
char get_choice(void) { int ch; printf("Enter the operation of your choice:\n"); printf("a. add s. subtract\n"); printf("m. multiply d. divide\n"); printf("q. quit\n");
while ((ch = get_first()) != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q') {
printf("Please respond with a, s, m,d, or q.\n");
}
return ch;
}
float get_num(void) { float num; char ch;
while (scanf("%f", &num) != 1) {
while ((ch = getchar()) != '\n') {
putchar(ch);
}
printf(" is not a number.\n");
printf("Please enter a number,such as 2.5, -1.78E8, or 3: ");
}
return num;
}
char get_first(void) { int ch; ch = getchar();
while (isspace(ch)) {
ch = getchar();
}
while (getchar() != '\n')
continue;
return ch;
原文地址: https://www.cveoy.top/t/topic/fZGT 著作权归作者所有。请勿转载和采集!