2017-06-02 63 views
-2

當我運行此我得到正確的答案,如果語句的外面,和錯誤的if語句裏面.. EX 3和3的長度和寬度給了我9,但內部條件它給了我92 .. 我曾嘗試雙浮INT ... 任何幫助將是巨大的......C++給了我2個不同的答案,基本的計算

cout << "you entered 2 for Rectangle\n"; 
cout << "Enter the length of the Rectangle.\n"; 
cin >> lengthRec; 

cout << "Enter the width of the Rectangle.\n"; 
cin >> widthRec; 

areaRec = lengthRec * widthRec; 
cout << areaRec; 

if ((lengthRec > 0) && (widthRec > 0)) { 
    areaRec = lengthRec * widthRec; 
    cout << "\nlength is " << lengthRec << "\n"<< "width is " << 
    widthRec << "\n"; 
    cout << "The area is "; 
    cout << areaRec; 
} 
else { 
    cout << "Invalid entry, Please re run with a positive number\n"; 
} 
+4

[無法重現](http://coliru.stacked-crooked.com/a/73101508f1a55aaf)。請發佈您的實際代碼。很可能,因爲你沒有在'areaRec'之後寫一個換行符,所以在程序的後面寫出一個「2」,兩個數字相鄰。 – cdhowie

+0

它看起來像'if'語句中的代碼正常工作,打印9和2打印稍後的地方。嘗試將'cout << areaRec;'更改爲'cout << areaRec <<「垃圾:」';你明白我的意思。 – KCH

+0

Ahhh ....非常感謝,我在代碼底部有一個選擇檢查,那是什麼導致這個...非常感謝你!我的第一個問題,我很緊張...... –

回答

0

優秀作品沒有任何問題 - 別的東西篡改後的O/p線,因爲你不要有'\ n'

#include <iostream> 
#include <stdio.h> 
#include <iostream> 

using namespace std; 

int main(){ 
    int lengthRec, widthRec, areaRec; 
    cout << "you entered 2 for Rectangle\n"; 
    cout << "Enter the length of the Rectangle.\n"; 
    cin >> lengthRec; 

    cout << "Enter the width of the Rectangle.\n"; 
    cin >> widthRec; //CHECK HERE 

    areaRec = lengthRec * widthRec; 
    cout << areaRec<<"\n"; 

    if ((lengthRec > 0) && (widthRec > 0)) { 

     areaRec = lengthRec * widthRec; 
     cout << "\nlength is " << lengthRec << "\n"<< "width is " << 
     widthRec << "\n"; 
     cout << "The area is "; 
     cout << areaRec<<"\n"; //CHECK HERE 
    } 
    else { 
     cout << "Invalid entry, Please re run with a positive number\n"; 
    } 
    return 0; 
} 

輸出: -

you entered 2 for Rectangle 
Enter the length of the Rectangle. 
Enter the width of the Rectangle. 
9 
length is 3 
width is 3 
The area is 9 
+0

說它正常工作不是一個答案。如果您想展示演示,請在評論中發佈鏈接到像ideone.com或rextester.com這樣的網站。 – Barmar

+0

@Barmar:明白了! – Zakir

相關問題