1

由于某种原因,即使我没有将它分配给数组中的一组数字,也会输出“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;
4

2 回答 2

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;
}
于 2013-02-24T03:51:46.670 回答
0

你在滥用setNums,你根本不需要它。只需这样做:

int choice = rand() % size + 1;
于 2013-02-24T03:53:53.080 回答