我只想让用户输入一些数字.如果数字为-1,则程序停止然后输出相同的数字.为什么这么难?我不明白为什么逻辑不在这里工作.
例如,当用户输入:
1 2 3 -1
Run Code Online (Sandbox Code Playgroud)
然后该程序应打印出来:1 2 3 -1
#include <iostream>
using namespace std;
int main()
{
int input, index=0;
int array[200];
do
{
cin >> input;
array[index++]=input;
} while(input>0);
for(int i=0; i < index; i++)
{
cout << array[index] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
改变这个
for(int i=0; i < index; i++)
{
cout << array[index] << endl;
}
Run Code Online (Sandbox Code Playgroud)
至
for(int i=0; i < index; i++)
{
cout << array[i] << endl;
}
Run Code Online (Sandbox Code Playgroud)
您index在seconde循环中使用,导致程序在用户输入后打印所有数组单元格.
此外,如果-1你的条件是你应该改为
} while(input>=0);
^^
Run Code Online (Sandbox Code Playgroud)
否则,0也会停止循环,这不是你要求的.
| 归档时间: |
|
| 查看次数: |
1952 次 |
| 最近记录: |