一个入门级的问题:编写程序对表达式求职

C语言 码拜 7年前 (2017-04-18) 836次浏览
运行的时候要把表达式输两遍才能出结果
不知道哪里出了问题 /(ㄒoㄒ)/~~
刚开始学 多多指点
#include <stdio.h>
#include <stdlib.h>
int main()
{
float operand,sum;
char ch;
printf(“Enter an expression:”);
scanf(“%f”,&operand);
sum=operand;
while (ch!=”\n”)
{
scanf(“%c”,&ch);
scanf(“%f”,&operand);
switch (ch)
{
case “+”:
sum += operand;
break;
case “-“:
sum -= operand;
break;
case “*”:
sum *= operand;
break;
case “/”:
sum /= operand;
break;
}
}
printf(“Value of expression:%.1f\n”,sum);
return 0;
}
解决方案

60

原因是你一次while循环后,你的ch并不等于”\n”,感觉你scanf(“%c”, &ch);应该换个位置

#include <stdio.h>
#include <stdlib.h>
int main()
{
	float operand, sum;
	char ch = " ";
	printf("Enter an expression:");
	scanf("%f", &operand);
	scanf("%c", &ch);
	sum = operand;
	while (ch != "\n")
	{
		scanf("%f", &operand);
		switch (ch)
		{
		case "+":
			sum += operand;
			break;
		case "-":
			sum -= operand;
			break;
		case "*":
			sum *= operand;
			break;
		case "/":
			sum /= operand;
			break;
		}
		scanf("%c", &ch);
	}
	printf("Value of expression:%.1f\n", sum);
	return 0;
}

20

scanf(“%c”,&ch); 会将之前输入留下的换行符 \n接收了
改成ch = getchar();

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明一个入门级的问题:编写程序对表达式求职
喜欢 (0)
[1034331897@qq.com]
分享 (0)