我的for循环遇到了一些麻烦,我想在for循环中的一个int数组中输入1个数字,循环4次.但是输出立即变为"请输入第4个数字",好像变量i从一开始就是4.
#include <iostream>
#include <string>
#include <iostream>
using namespace std;
void main()
{
int PIN[4] = {};
string txtNr ="1st";
for(int i=0;i<4;i++)
{
if(i=0)
txtNr = "1st";
if(i=1)
txtNr = "2nd";
if(i=2)
txtNr = "3rd";
if(i=3)
txtNr = "4th";
cout << "Please enter the " << txtNr <<" number: ";
cin >> PIN[i];
}
for(int i=0;i<4;i++)
{
cout << PIN[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
有人知道吗?如果我输入一个数字,例如最后一个输出
0 0 0 1
更改=为==检查if(...)语句中的相等性.
只是简单地=改变了价值i,就像通常的任务一样.
另外,我建议你阅读谷歌的C++ Style Guide.
之后,您的代码应如下所示:
#include <iostream>
#include <string>
#include <iostream>
using namespace std;
void main()
{
int PIN[4] = {};
string txtNr ="1st";
for(int i=0;i<4;i++)
{
if(i == 0)
txtNr = "1st";
if(i == 1)
txtNr = "2nd";
if(i == 2)
txtNr = "3rd";
if(i == 3)
txtNr = "4th";
cout << "Please enter the " << txtNr <<" number: ";
cin >> PIN[i];
}
for(int i=0;i<4;i++)
{
cout << PIN[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)