新手代码,大佬勿喷,自己学习过程中的一些记录。
#include<stdio.h>
void show_menu(void);
double input_first(void);
double input_second(char ch);
void output_result(char ch, double num1,double num2);
int main()
{
double num1 = 0.0, num2 = 0.0;
char ch;
show_menu();
ch = getchar();
while (ch != 'q')
{
//input
num1 = input_first();
num2 = input_second(ch);
//output
output_result(ch, num1, num2);
show_menu();
ch = getchar();
while (ch != 'a' && ch != 'm' && ch != 'd' && ch != 's' && ch != 'q')
ch = getchar();
}
printf("Bye!");
return 0;
}
void show_menu(void)
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
}
double input_first(void)
{
double n=0;
int check;
char ch;
printf("Enter first number:");
while (scanf("%lf",&n)!=1)
{
while ((ch= getchar()) != '\n')
putchar(ch);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
}
return n;
}
double input_second(char ch)
{
double n;
int check;
char cha;
printf("Enter second number:");
check = scanf("%lf", &n);
while((check==0)||(ch=='d'&&n==0))
{
if (ch == 'd' && n == 0)
{
printf("Enter a number other than 0:");
check = scanf("%lf", &n);
continue;
}
else {
while ((cha = getchar()) != '\n')
putchar(cha);
printf(" is not an number.\n");
printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
check = scanf("%lf", &n);
continue;
}
}
return n;
}
void output_result(char ch, double num1, double num2)
{
if (ch == 'a')
printf("%.1f + %.1f = %.1f\n", num1, num2, num1 + num2);
else if (ch == 's')
printf("%.1f - %.1f = %.1f\n", num1, num2, num1 - num2);
else if (ch == 'm')
printf("%.1f * %.1f = %.1f\n", num1, num2, num1 * num2);
else if (ch == 'd')
printf("%.1f / %.1f = %.1f\n", num1, num2, num1 / num2);
}
这篇博客记录了作者在学习C Primer Plus第六版时,针对编程练习8.11.8的过程和心得,主要展示了一个新手在学习C语言时的实践与思考。
313

被折叠的 条评论
为什么被折叠?



