C 给我2个基本计算的不同答案

C++ giving me 2 different answers to basic calculation

本文关键字:答案 计算 给我 2个      更新时间:2023-10-16

当我运行此操作时,我在if语句之外得到正确的答案,而在if语句中的错误答案。前3和3的长度和宽度给了我9,但在内部条件下它给了我92。我尝试了Double Float int ...任何帮助都很棒...

cout << "you entered 2 for Rectanglen";
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 numbern";
}

效果很好,没有问题 - 以后再设计,因为您没有' n'

#include <iostream>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
    int lengthRec, widthRec, areaRec;
    cout << "you entered 2 for Rectanglen";
    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 numbern";
    }
    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