C++返回错误的代码行

C++ Returning Wrong Line of Code

本文关键字:代码 错误 返回 C++      更新时间:2023-10-16

我被指示设计一种算法,允许用户计算矩形的周长和面积,但这太简单了:

Perimeter = 2 (Length + Width)
Area = (Length * Width)

我想使用与我的教授在第一天向我们展示的类似的结构来构建一个程序,以便我可以让一个程序从用户那里收集数据,为我计算矩形的周长和面积,然后将答案输出回用户。这很容易,所以我决定让程序也告诉我用户输入的长度和宽度是矩形还是正方形的长度和宽度。

使用我编写的代码,程序始终返回输入的长度和宽度是正方形的长度和宽度。我不确定我哪里出错了:

这是我的代码:

#include<iostream>
using namespace std;
int main() {
    //Declaration
    int length;
    int width;
    int perimeter;
    int area;
    //Collect Data
    cout << "Let's calculate the perimeter and area of a rectanglen";
    cout << "What is the length of the rectangle?: ";
    cin >> (length);
    cout << "What is the width of the rectangle?: ";
    cin >> (width);
    //Calculation
    (perimeter) = 2 * (length + width);
    (area) = (length) * (width);
    //Output Data
    cout << "The perimeter of the rectangle is: " << (perimeter) << "n";
    cout << "The area of the rectangle is: " << (area) << "n";
    //For some reason, the code is not able to recognize what I have designed.
    //No matter what input for length and width, when the program executes it returns that I entered the length and width of a square.
    if ((length) = (width))
        cout << "Hey! You entered the length and width of a Square!n";
    else
        cout << "You entered the length and width of a Rectangle!n";
    system("pause");
    return 0;
}

任何帮助将不胜感激!非常感谢!

你想要一个双等号:

if (length == width)

单等号(=(执行赋值,双等号(==(执行比较。

在你的 if 语句中,你把width分配给length而不是比较

它应该是:if (length == width)

你的 if 语句之所以计算结果为 true,是因为它检查求值的结果(即 length 的值(是否与零不同。

这是因为bool在内部表示为int,其中false被定义为0true其他。

而且由于width通常不0因此总是会导致true。 您可以通过输入 0 来测试它 width .

我建议的一件事是研究使用调试器来单步执行代码的每一行,因为它一次运行一行。如果您使用的是VS,那么您就内置了一个!

我认为如果您使用调试器,您会注意到当 if 运行时,它正在执行分配而不是比较。只是对未来的一个想法。

我相信每个人都可以说他们已经用调试器捕获了许多愚蠢的错误。干得好:)