一、题目链接
http://noi.openjudge.cn/ch0104/19/
二、解题思路
◎ 指定的两个操作数和一个操作符,运算时存在六种可能性;
→ 如果操作符为+号,则操作数做加法;
否则如果操作符为-号,则操作数做减法;
否则如果操作符为*号,则操作数做乘法;
否则如果操作符为/号且除数不为0,则操作数做除法;
否则如果操作符为/号(且除数不为0),则属于除0操作,括号内的内容在程序中可以忽略;
否则,操作符违法;
以上六种可能性是互斥的。
三、实施步骤
◎ 首先,定义并输入两个int类型的整数x、y,分别代表第一操作数、第二操作数;
◎ 其次,定义并输入char类型的字符c,代表操作符;
◎ 然后:
→ 如果c=='+',输出x+y;
否则如果c=='-',输出x-y;
否则如果c=='*',输出x*y;
否则如果c=='/'&&y!=0,输出x/y;
否则如果c=='/',输出Divided by zero!;
否则,输出Invalid operator!。
四、Java程序
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
char c = input.next().charAt(0);
if (c == '+') {
System.out.print(x + y);
}
else if (c == '-') {
System.out.print(x - y);
}
else if (c == '*') {
System.out.print(x * y);
}
else if (c == '/' && y != 0) {
System.out.print(x / y);
}
else if (c == '/') {
System.out.print("Divided by zero!");
}
else {
System.out.print("Invalid operator!");
}
}
}
五、C++程序
#include <iostream>
using namespace std;
int main()
{
int x;
int y;
char c;
cin >> x;
cin >> y;
cin.get();
cin.get(c);
if (c == '+')
{
cout << x + y;
}
else if (c == '-')
{
cout << x - y;
}
else if (c == '*')
{
cout << x * y;
}
else if (c == '/' && y != 0)
{
cout << x / y;
}
else if (c == '/')
{
cout << "Divided by zero!";
}
else
{
cout << "Invalid operator!";
}
return 0;
}