C语言程序设计基础|算数式判断

  • Post author:
  • Post category:其他


题目描述:

用户输入一个算术运算的式子,运算包括了+、-、*、/、%,首先输出该式子,如果运算符不在这5种操作内,输出运算符错误的信息;如果式子是正确的,输出式子正确的相应信息;如果式子是错误的,输出式子错误的相应信息。例如:

输入:1+2=3

输出:1+2=3 correct

输入:2/3=8

输出:2/3=8 wrong

输入:6&7=12

输出:6&7=12 error op

输入要求:

一个算术式子

输出要求:

该式子以及对错信息

#include<iostream>
using namespace std;

int main() {
	int a, b, c;
	char d, e;
	cin >> a >> d >> b >> e >> c;
	if (d == '+' || d == '-' || d == '*' || d == '/' || d == '%') {
		switch (d) {//利用选择结构来判断符号
		case('+'):if (a + b == c) {
			cout << a << d << b << e << c << " correct" << endl;
		}
				 else cout << a << d << b << e << c << " wrong" << endl;
			break;
		case('-'):if (a - b == c) {
			cout << a << d << b << e << c << " correct" << endl;
		}
				 else cout << a << d << b << e << c << " wrong" << endl;
			break;
		case('*'):if (a * b == c) {
			cout << a << d << b << e << c << " correct" << endl;
		}
				 else cout << a << d << b << e << c << " wrong" << endl;
			break;
		case('/'):if (a / b == c) {
			cout << a << d << b << e << c << " correct" << endl;
		}
				 else cout << a << d << b << e << c << " wrong" << endl;
			break;
		case('%'):if (a % b == c) {
			cout << a << d << b << e << c << " correct" << endl;
		}
				 else cout << a << d << b << e << c << " wrong" << endl;
			break;
		}
	}
	else cout << a << d << b << e << c << " error op" << endl;
	return 0;
}

如有更简单的方法请赐教~~



版权声明:本文为2203_75720729原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。