gpt4 book ai didi

c++ - 尽管达到退出条件,循环仍在重复

转载 作者:行者123 更新时间:2023-11-28 04:14:38 26 4
gpt4 key购买 nike

我有一个试图构建直角三角形的小程序。

程序给出的边界是底和高都必须在[10,20]范围内。

该代码似乎可以很好地构建 [10,19] 范围内的三角形。然而,在 [n,20] 或 [20,n] 的边界条件下,输出变得困惑并且拒绝退出生成三角形中间(底线和顶线之间)的 for 循环。

如果您能协助查明问题,我将不胜感激。

我已经研究过这个问题,但我没有实践,应该被视为新手。

问题肯定出在“BUILD”注释之后的 while 或嵌套 for 循环。

请注意,在所提供的代码块级之上可能定义了一两个不相关的变量。

//TRIANGLE// 
if (shapeselect=2)
{
int base;
int height;
//prompt use for base measurement//
cout<<"Please select the size of the BASE of your triangle, in the range [10,20]\n"<<endl;
cin>>base;
while (base!=10&&base!=11&&base!=12&&base!=13&&base!=14&&base!=15&&base!=16&&base!=17&&base!=18&&base!=19&&base!=20)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<"You have entered an invalid value.\nPlease enter a valid value for the BASE of your triangle in the range of [10,20].\n";
cin>>base;
}
//prompt user for height measurement//
cout<<"Please select the size of the HEIGHT of your triangle, in the range of [10,20].\n";
cin>>height;
while (height!=10&&height!=11&&height!=12&&height!=13&&height!=14&&height!=15&&height!=16&&height!=17&&height!=18&&height!=19&&height!=20)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout<<"You have entered an invalid value.\nPlease enter a valid value for the HEIGHT of your triangle, in the range [10,20].\n";
cin>>base;
}
//BUILD TRIANGLE//
string bottom(base, '*');
string top="*";
int middlerows=height-1;
cout<<top<<endl;
while (middlerows!=1)
{
int middlespacechars;
for (middlespacechars=0; middlespacechars!=base-2; ++middlespacechars)
{
string middlespace(middlespacechars, ' ');
cout<<"*"<<middlespace<<"*\n";
--middlerows;
}
}
cout<<bottom<<"\n"<<endl;
cout<<"^TRIANGLE\n";
cout<<"BASE = "<<base<<endl;
cout<<"HEIGHT = "<<height<<endl;
cout<<goodbye<<"\n"<<endl;
}

}

三角形顶部打印(单个“*”)。然后三角形的中间部分无限重复(星号之间有空格)。统计行数,好像是到了base-2 spaces的情况,但是没有exit。它似乎到达“19/20”行。

最佳答案

经过一些调试后,对于 base != height 的任何输入,您的代码似乎会中断。

问题出在您的 for循环 - 你在 while 中的逻辑中间行应该从 height-1 开始倒计时的循环直到它达到 1是正确的,但在 for ,如果 base 和 height 不相同,您会遇到问题 - 循环强制 middlerows 为负值,这会导致它错过 middlerows != 1 的转义条件。 .

例如,如果用户输入 11, 15 ,然后在第一次运行时,middlerows 将为 14,for 循环将从 0 计数到 9(height-2),每次递减 middlerows。在此循环结束时,您的中间行数现在为 5。5 != 1 , 因此循环将再次运行。

再次运行后,middlerows 为-4。 -4 != 1 ,所以循环再次运行,将中间行下降到 -13... 然后它一直下降,直到永远(或者直到你环绕并幸运地以某种方式完美地击中 middlerows=1 )。

关于c++ - 尽管达到退出条件,循环仍在重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944460/

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