C Primer Plus (第6版)编程练习8.11.8

这篇博客记录了作者在学习C Primer Plus第六版时,针对编程练习8.11.8的过程和心得,主要展示了一个新手在学习C语言时的实践与思考。

新手代码,大佬勿喷,自己学习过程中的一些记录。

#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);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值