我该怎么用num替换?

时间:2016-01-16 02:49:08

标签: c++ sum product

我试图编写一个程序来确定两个整数的和和是偶数还是奇数。

一切似乎都很好,除非我运行程序时,它出来了:" 2和3的乘积是5并且是偶数。"甚至?

为什么即使它应该是奇怪的呢?现在根据我的理解,它正在阅读num,因为我提出了(num%2==0),这就是为什么它说的均匀。如何让它读取两个数字(总和/产品)的结果?

    #include<iostream>
    using namespace std;
    int main ()
    {
        int num; 
        cout << "Please enter an integer: ";
        cin >> num;

        int num2;
        cout << "Please enter another integer: ";
        cin >> num2;

    if ( num % 2 == 0 )
    {
        cout << "The product of " << num << " and " << num2 << " is " << num*num2 << " and is even." << endl;
        cout << "The sum of " << num << " and " << num2 << " is " << num+num2 << " and is even." << endl;
    } 

    else
    {
        cout << "The product of " << num << " and " << num2 << " is " << num*num2 << " and is odd." << endl;
        cout << "The sum of " << num << " and " << num2 << " is " << num+num2 << " and is odd." << endl;   
    } 
        return (0);
    }

1 个答案:

答案 0 :(得分:2)

您只需检查num是否均匀。相反,您应该计算产品和总和,并检查它们:

int sum = num + num2;
int product = num * num2;

if (sum % 2 == 0 && product % 2 == 0) {
   cout << sum and product are both even << endl;
} else {
   cout << sum and product are not both even << endl;
}