由于某种原因,即使我没有将它分配给数组中的数字集,也会输出“0”。我怎样才能摆脱零?
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
int n;
int size=10;
int setNums[10];
int main()
{
string ans = "";
do {
for (int n=0; n<size;n++ )
{
setNums[size] = n+1;\
cout << setNums[size] << endl;
}
srand (time(NULL));
int choice = rand() % setNums[size];
cout << choice << endl;
cout << "Keep guessing?" << endl;
cin >> ans;
} while (ans == "Y");
cout << "\n\n...Press ENTER to Exit System...";
cin.get();
return 0;
答案 0 :(得分:2)
你想要的是找到索引,而不是值本身。改变这个:
int choice = rand() % setNums[size];
到此:
int choice = setNums[rand() % size];
,始终在索引size
上执行分配。你应该:
...
for (int n=0; n<size;n++ ) {
setNums[n] = n+1;\
cout << setNums[n] << endl;
}
答案 1 :(得分:0)
你误导setNums
,根本不需要它。就这样做:
int choice = rand() % size + 1;