多年来我也一直在努力寻找这个问题,但我似乎无法理解它。 当输入大于 2 的数字时,程序只是不断地输出 ' ' 或 '*' 而不会终止,并给出正确的输出。
谁能看出我做错了什么?这是我的代码:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
int xx;
cout << "Enter the Height (odd positive numbers only): " << endl;
cin >> xx;
for(float y; y < xx; y++)
{
for(float x; x < xx; x++)
{
x = abs( x - ( xx / 2 ) );
y = abs( y - ( xx / 2 ) );
if( ( x + y ) <= ( xx / 2 ) )
cout << '*';
else
cout << ' ';
}
cout << endl;
}
return 0;
最佳答案
首先,存在未定义的行为。 x
和y
需要初始化。
其次,您的 x
和 y
永远不会大于 xx
(如果 xx>=2
) 因为你有:
x = abs( x - ( xx / 2 ) );
y = abs( y - ( xx / 2 ) );
因此无限循环。
关于c++ - 连续 for 循环不会终止 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562400/