2015-02-09 76 views
-3

我正在爲一個開始的C++類進行家庭作業分配,並且我有點失落。
這是作業:如果初始輸入是C++中的奇數整數,則將兩個整數相乘

創建一個C++程序,要求用戶輸入一個數字。

該程序的輸出應該是以下之一: 您輸入了一個偶數。 或 您輸入了一個奇數。

如果用戶輸入一個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() 
+4

你問第二個數字,然後做:'cin >> num1 >> endl;'不應該在'num2'中?你也說你得到很多錯誤,但實際上並沒有告訴我們這些錯誤是什麼。 (PS:'cout << num'這是無效的,你沒有聲明'num'作爲一個變量) – Borgleader 2015-02-09 21:32:57

+0

你應該記得從'main'返回一個值(而不是讓控制權流走)。 – inetknght 2015-02-09 21:34:56

+0

我認爲語法高亮顯得很明顯,你在那裏有一些流浪的智能引號。 'cin >> endl;'應該消失。 @inetknght,當流出'main'的末尾時返回0。 – chris 2015-02-09 21:35:47

回答

0

爲奇數值

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; 
      } 
+0

我看到的唯一變化是'num1'沒有被賦值乘法的結果,這是好的,但是沒有可觀察到的差別。 – chris 2015-02-09 21:37:04

+0

但該代碼正在計算num1 * num2。 OPs代碼沒有。所以這是一個改進:) – moobi 2015-02-09 21:39:45

+0

是的,我確實錯過了輸入中的s/num1/num2 /。突出顯示改變的內容通常是一個好主意,這就是一個很好的例子。 – chris 2015-02-09 21:41:14

2
#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變量,應該是num1,也是cin >> endl錯誤。

什麼是意想不到的,你的最後不是"但是別的,它會產生很多錯誤。

0

更正

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; 
} 

後不要放置quotaion標記之間的公式。這將它們變成字符串或字符,不能像願望一樣執行。即cout << " Your two numbers multiplied equals (num1 *= num2)」 << endl;

將語句cout << " Your two numbers multiplied equals (num1 *= num2)」 << endl;置於if語句的外側,即使該語句不是奇數,也會導致語句運行。這不符合任務。和num2爲空仍然會導致錯誤