C++返回错误的代码行
C++ Returning Wrong Line of Code
我被指示设计一种算法,允许用户计算矩形的周长和面积,但这太简单了:
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
被定义为0
,true
其他。
而且由于width
通常不0
因此总是会导致true
。 您可以通过输入 0
来测试它 width
.
我建议的一件事是研究使用调试器来单步执行代码的每一行,因为它一次运行一行。如果您使用的是VS,那么您就内置了一个!
我认为如果您使用调试器,您会注意到当 if 运行时,它正在执行分配而不是比较。只是对未来的一个想法。
我相信每个人都可以说他们已经用调试器捕获了许多愚蠢的错误。干得好:)
相关文章:
- 将鼠标悬停在问题上时与预期">"相关的代码错误
- VI工作室代码错误无法打开输出文件主.exe
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 有关矩阵的代码错误导致分段错误(内核转储)
- C++ Schannel POST 400 错误代码错误请求
- Java 本机访问代码错误:"Invalid memory access"
- 代码错误修改
- C++代码错误分配
- "_FCbuild"不能用作函数 - C/C++ 代码错误
- 我的代码错误类型警告 1 警告 C4018 和更多错误
- 代码错误(从 1 到 100 找到质数)
- OpenCV VisualStudio,C 代码错误尝试访问像素
- 当我使用的教程完全没有错误时,为什么我的代码错误
- 简单的NOOB C 输入/输出问题:代码错误
- 为什么enumProcessModules返回false值和299代码错误
- WinhttpSetoption()失败设置TLSV1.2,带有错误代码错误_internet_incorrect_ha
- 苹果安全传输代码错误
- C++ - 国际象棋主教移动代码错误
- 导入Python库时,嵌入了Python代码错误
- 编译提升C 代码错误