Mon*_*MFR 2 c++ integer multiplication addition
我遇到一个简单的程序有问题,它将乘以2个整数并打印输出,确定它是偶数还是奇数.它还将在开头添加2个整数输入,并在下一行中执行相同操作.乘法工作正常,如果产品是偶数或奇数,则显示.但是,添加不是这样做的,我不明白为什么.这是我的代码:
#include <iostream>
using namespace std;
int main (){
int a, b;
cout << "Please enter an integer: ";
cin >> a;
cout << "Please enter another integer: ";
cin >> b;
if (a*b %2== 0){
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is even." << endl;
}
else {
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is odd." << endl;
};
if (a+b %2== 0){
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is even." << endl;
}
else {
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is odd." << endl;
}
return (0);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助和解释将不胜感激.谢谢!
基本上%是在处理之前+,所以你的测试:
if (a+b % 2 == 0)
Run Code Online (Sandbox Code Playgroud)
好像是
if (a + (b%2) == 0)
Run Code Online (Sandbox Code Playgroud)
不使一大堆的道理,并且很少会是真实的,除非两者b是连和 a是0.
所有这一切都与乘法(做业务*,/,%)具有相同的优先级,由左到右的处理,所以
if (a*b % 2 == 0)
Run Code Online (Sandbox Code Playgroud)
工作得很好,如:
if ((a*b) % 2 == 0)
Run Code Online (Sandbox Code Playgroud)
这恰好是你真正的意思.
但是,这些乘法运算在与加法(+,-)相关的操作之前处理.所以%在之前分组+,导致您的具体问题.
你可能已经了解了学校的操作顺序,比如我被教过BODMAS.相同的规则适用于C++.
就个人而言,我发现最好在任何类型的复合表达中使用括号,即使它不是绝对必要的.它可以使代码更容易阅读,而不是试图记住你头脑中的所有规则.所以我更喜欢:
if ((a*b) % 2 == 0) // ...
if ((a+b) % 2 == 0) // ...
Run Code Online (Sandbox Code Playgroud)
即使第一个中的额外括号并非真正需要.