如果初始输入是C++中的奇整数,则两个整数相乘

Multiplying two integers if initial input is an odd integer in C++

本文关键字:整数 两个 如果 输入 C++      更新时间:2023-10-16

我正在为一堂刚开始的C++课做家庭作业,我有点不知所措
任务如下:

创建一个c++程序,要求用户输入一个数字。

程序的输出应为以下内容之一:您输入了一个EVEN号码。或您输入了ODD号码。

如果用户输入了ODD号码,请他们输入另一个号码。将这个数字乘以第一个数字并输出结果。

偶数/奇数部分很容易——我已经完成了这个部分。我对第二部分完全迷失了方向。我的错误太多了,我甚至不知道开始在哪里。如果有人能给我一个提示,告诉我我做错了什么,我将不胜感激。

#include <iostream>
using namespace std;
int main () {
        int num1; // This is the original number entered by the user.
        int num2; // This is the second number entered if the first number is odd.
        cout << "Enter a number: "<< endl;
        cin >> num1 >> endl;
        if (num1 % 2 == 0) {
                cout << num << " Your number is even." << endl;
}       if (num1 % 2 != 0) {
                cout << num1 << " Your number is odd. Please enter another number: “<< endl;
                cin >> num1 >> endl;
        } // end of if odd
        cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;
} // end of main ()
#include <iostream>
using namespace std;
int main () {
    int num1; // This is the original number entered by the user.
    int num2; // This is the second number entered if the first number is odd.
    cout << "Enter a number: "<< endl;
    cin >> num1;
    if (num1 % 2 == 0) {
        cout << num1 << " Your number is even." << endl;
    }       
    else {
        cout << num1 << " Your number is odd. Please enter another number: " << endl;
        cin >> num2;
        cout << " Your two numbers multiplied equals " << num1*num2 << endl;
    } // end of if odd
    return 0;        
} // end of main ()

这是固定代码。您尝试了cout << num,但没有num变量,应该是num1cin >> endl也是错误的。

出乎意料的是,你最后的不是",而是其他东西,它会产生很多错误。

奇数值的部分

if (num1 % 2 != 0) {
    cout << num1 << " Your number is odd. Please enter another number: “<< endl;
    cin >> num2 >> endl;
    cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl;
            }
修正后的

if (num1 % 2 != 0) {
cout << num1 << " Your number is odd. Please enter another number:"<< endl;
cin >> num2;
cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl;
}

不要把公式放在引号之间。这会将它们变成字符串或字符,无法按需执行。即cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;

如果将语句cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;放在if语句之外,则即使数字不是奇数,也会运行该语句。这与作业不符。并且num2为空仍将导致错误