我在将数组从函数返回到主函数时遇到麻烦。该数组还用作另一个函数的参数。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
void ran(int list[]);
void guess(int list[]);
int black_marker(int num1[], int num2[]);
int main(){
int r[4];
int g[4];
cout << black_marker(ran(r), guess(g));
}
void ran(int list[]){ //random number generator
srand (time(NULL));
int a = rand() % 6 + 1;
int b = rand() % 7 + 1;
while(a == b)
b = rand() % 7 + 1;
int c = rand() % 8 + 1;
while(a == c || b == c)
c = rand() % 8 + 1;
int d = rand() % 9 + 1;
while(a == d || b == d || c == d)
d = rand() % 9 + 1;
int num_random[4] = {a, b, c, d};
}
void guess(int list[]){ //takes user input for a guess
int random_no[4];
for(int i = 0; i < 4; i++){
cin >> random_no[i];
}
}
int black_marker(int num1[], int num2[]){ //Counts how many digits from random number
int black_count = 0; //is similar to the user's guess
for(int i = 0; i < 4; i++){
if(num1[i] == num2[i]){
black_count += 1;
}
}
return black_count;
}
基本上,这是一个不完整的猜数字游戏,在该游戏中,会为用户提供提示,例如随机生成的数字和用户输入的猜测所共有的数字位数。我收到一个cout << black_marker(ran(r), guess(g));
不常见的void类型错误,因为当我在void函数的主体中有cout语句时,此按引用传递方法会起作用。
black_marker(ran(r), guess(g))
black_marker
有两个数组,但ran()
并guess(g)
返回void,所以你结了black_marker(void, void)
,并且将无法正常工作。
你想做的是
#include <cmath>
#include <iostream>
using namespace std;
void ran(int list[]){ //random number generator
srand (time(NULL));
int a = rand() % 6 + 1;
int b = rand() % 7 + 1;
while(a == b)
b = rand() % 7 + 1;
int c = rand() % 8 + 1;
while(a == c || b == c)
c = rand() % 8 + 1;
int d = rand() % 9 + 1;
while(a == d || b == d || c == d)
d = rand() % 9 + 1;
list[0] = a;
list[1] = b;
list[2] = c;
list[3] = d;
}
void guess(int list[]){ //takes user input for a guess
int random_no[4];
for(int i = 0; i < 4; i++){
cin >> list[i];
}
}
int black_marker(int num1[], int num2[]){ //Counts how many digits from random number
int black_count = 0; //is similar to the user's guess
for(int i = 0; i < 4; i++){
if(num1[i] == num2[i]){
black_count += 1;
}
}
return black_count;
}
int main(){
int r[4];
int g[4];
ran(r);
guess(g);
cout << black_marker(r, g) << endl;
}
但是,您应该删除C样式的数组,并使用std::vector
或std::array
代替。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句