找不到循环的位置,有人可以帮助找到它吗
在我看来,所有的循环都关闭了。
我应该使用 for 循环来打印出垂直条形图,但它似乎在循环
#include <iostream>
using namespace std;
int main()
{
const int MAX=100;
int array[MAX];
int highest=0;
for (int counter=0; counter<MAX; counter++) {
cin>>array[counter];
if(array[counter]==0){
for (int check=0; check<=counter; check++) {
if(array[check]>highest)
highest=array[check];
}
for (int rows=highest;rows>=1;rows--) {
for (int cols=0; cols<=26; cols++) {
if (array[cols]>=rows)
cout<<"* ";
else
cout<<" ";
}
cout<<endl;
}
}
}
return 0;
}
有几个
地方使用未初始化的值。
改变
int highest = array[0]; // array[0] is uninitialized
自
int highest = 0;
改变
for(int find = 0;find<=25;find++) // Not all elements of // array have been initialized.
自
for(int find = 0;find<=counter;find++)
我不能保证你的其他代码片段的逻辑有效性。
代码中的错误包括:
- 使用不确定值初始化
highest
。 - 只有当有人输入
0
时,你的输出分支才会被采用,而不是在有人输入 25 个实际数字时。 - 您永远不会验证任何给定值的输入是否实际成功
- 输出回路的限制是错误的。您可以(并且将)在
array[]
中评估不确定的内容,如果输入循环过早终止0
输入值。 i < 1
循环是完全没有必要的。highest
的计算可以/应该在输入期间完成;之后不需要完成。- 您应该使用无符号值。这些都不允许输入负数。
考虑到以上所有因素。
#include <iostream>
int main()
{
unsigned int arr[25] = {0}, highest=0;
int len = 0;
for (; len < 25 && std::cin >> arr[len] && arr[len] > 0; ++len)
{
if (highest < arr[len])
highest = arr[len];
}
while (highest--)
{
for (int i=0; i<len; ++i)
std::cout << ((highest < arr[i]) ? '*' : ' ') << ' ';
std::cout << 'n';
}
}
输入
12 5 7 11 6 9 4 8 10 2 0
输出
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
祝你好运。
这是更正的程序:
- 我已经声明了一个宏 MAX 将数字设置为 25,以便可以用较少的数字进行调试。
- 相等情况已在 <=25 中删除,因为它不是由用户
- 为了清楚起见,我已经用所有 0 初始化了数组,因为我们不想要它与垃圾值一起检查
#include <iostream>
#define MAX 25
using namespace std;
int main() {
int array[100] = {0,};
int highest = array[0];
for (int counter = 0; counter < MAX; counter++){
cin >> array[counter];
if (array[counter] == 0){
for (int i = 0; i <1; i++){
for (int find = 0; find < MAX; find++){
if (array[find]>highest){
highest = array[find];
}
}
for (int rows = highest; rows >= 1; rows--){
for (int cols = 0; cols < MAX; cols++){
if (array[cols] >= rows){
cout << "* ";
}
else{
cout << " ";
}
}
cout << endl;
}
}
}
}
for (int counter = 0; counter < MAX; counter++){
cout << array[counter] << endl;
}
getchar();
return 0;
}
该程序并不像您声称的那样无限运行。效果很好。:)