gpt4 book ai didi

c++ - 为什么这会造成无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 14:21:11 24 4
gpt4 key购买 nike

#include <iostream>
#include <math.h>
using namespace std;

int main() {
double radius = 0.00;
double height = 0.00;
double width = 0.00;
double side = 0.00;
double Area = 0.00;
const double PI = atan(1.0)*4;
string input = "none";

while (input != "0") {
cout << "Shape Menu: \n (r) rectangle \n (s) square \n (c) circle \n (0) exit" << endl;
cin >> input;
if (input == "r"){
cout << "Please enter a floating point value for the height of the rectangle." << endl;
cin >> height;
cout << height;
while (height <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid. Please input a floating point value greater than 0.";
cin >> height;
}
cout << "Please enter a floating point value greater than 0 for the width of the rectangle." << endl;
cin >> width;
while (width <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid";
cin >> width;
}
Area = height*width;
cout << "The area of a rectangle with those dimensions is " << Area << "units squared." << endl;
}

else if(input == "s"){
cout << "Please enter a floating point value for the length of the side." << endl;
cin >> side;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = side*side;
cout << "The area of a square with those dimensions is " << Area << "units squared" << endl;
}

else if(input == "c"){
cout << "Please enter a floating point value for the length of the radius." << endl;
cin >> radius;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = radius*radius*PI;
cout << "The area of a circle with those dimensions is " << Area << "units squared." << endl;
}

else if(input == "0"){
break;
}

else{
cout << "Your input does not match one of the options suggested. Please type r, s, c to get the area of a shape, or type 0 to exit." << endl;

}
}

return 0;
}

我正在尝试编写一个程序,要求用户从形状菜单中进行选择,然后为每种类型请求特定输入以确定面积。我现在遇到的问题是,试图弄清楚当人们输入非数字的半径或高度和宽度的答案时如何引发错误。我尝试为矩形编写的错误适用于最初的错误输入,但是一旦提示用户选择另一个形状,如果再次出现输入错误,则会开始无限循环。

最佳答案

您正在使用 cin.clear() 和 cin.ignore(1000,'\n') 跳过矩形情况下的无效输入,这很好,但在其他情况下您没有这样做。

关于c++ - 为什么这会造成无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com