我想打印第一个数到4的数字,比如我有这个随机函数,我想看到第一个达到4次的数字。所以它是第一个将自己打印 4 次的数字。例如:
int n;
int count1 = 0;
int count2 = 0;
int count3 = 0;
while (true) {
cout << "Enter a number btween 1-3" << endl;
cin >> n;
if (n == 1) {
count1++;
}
if (n == 2) {
count2++;
}
if (n == 3) {
count3++;
}
if (count1 == 4) {
cout << "You printed the number 1 4 times!";
break;
}
if (count2 == 4) {
cout << "You printed the number 2 4 times!";
break;
}
if (count3 == 4) {
cout << "You printed the number 3 4 times!";
break;
}
但是如果是 1-1000 个数字而不是 1-3,我会怎么做呢?
我想这样做,但是在一个随机函数上 - 该数字的计数为 4 次的第一个数字打印该数字 -
int fun() {
srand(time(NULL));
return rand() % 3;
}
然后我想在 main 中做第一个达到例如 4 次的数字打印这个数字。
我尝试做这样的事情:
for (int i = 0; i < 31; i++) {
arr[fun()]++;
cout << arr[fun()];
if (arr[fun()] == 4) {
cout << arr[fun()];
}
}
最后一个答案超出范围。我的答案是只使用一个数组
while(1) {
int f = rand() % 3;
count[f]++;
cout << f << endl;
if (count[f] == 4) {
cout <<"4 times" <<f;
break;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句