gpt4 book ai didi

c - C 中的返回值函数

转载 作者:行者123 更新时间:2023-12-02 07:05:24 24 4
gpt4 key购买 nike

您好,我正在开发一个生成主代码的快速程序,用户必须猜测代码。在检查用户的猜测时,我使用 2 个函数,一个用于精确匹配,另一个用于接近匹配(他们得到的数字在主代码中但不在正确的位置)

例。主密码 1 2 3 4

用户 2 3 2 4 输出应该显示用户有 2 个接近匹配和 1 个完全匹配。我无法理解如何正确返回 int。

当我尝试在 Main 中打印它们时,我的输出只显示了 exactMatch 和 closeMatch 的默认值。任何见解将不胜感激。谢谢。

 #include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define CODELENGTH 4
#define NUMSYMBOLS 6


int MasterCode[4];
int guess[ 4 ];
int exactMatch;
int closeMatch=0;

void genCode (int MasterCode[])
{
int i=0;
int k;
while (i < CODELENGTH){

MasterCode[i] =rand() %NUMSYMBOLS +1;
i++;

}//end while loop.
for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", MasterCode[ k ] );
}

printf( "\n" );
}





void getGuess (int guess[])
{

int number = 0;

printf( "Please enter your list of 4 numbers between 1 and 6: " );
int j;
int k;
for ( j = 0 ; j < 4; j++ ) {
scanf( "%d", &number );
guess[ j ] = number;
}

printf( "Your array has these values: " );

for ( k = 0 ; k < 4; k++ ) {
printf( "%d ", guess[ k ] );
}

printf( "\n" );
}




int main (int argc, char **argv)
{
srand ( time(NULL) );

genCode(MasterCode);
getGuess(guess);
checkExactMatches(MasterCode, guess, exactMatch);
checkCloseMatches(MasterCode, guess, closeMatch);
printf("%d = Ending exactMatches \n", exactMatch);
printf("%d = Ending closeMatches \n", closeMatch);





}
int checkExactMatches (int MasterCode[], int guess[], int exactMatch )
{
int woot;
for(woot=0; woot<4; woot++){


if (MasterCode[woot] == guess[woot]){
printf("Exact Match found \n");
exactMatch ++;
printf( "%d = Guess \n" , guess[ woot ]);
printf( "%d = MasterCode \n", MasterCode[ woot ]);
printf("%d = exactMatch \n", exactMatch);

}// end if

if (MasterCode[woot] != guess[woot])
printf("No EXACT match \n");


}//end for loop

return exactMatch;
} // end checkExactMatches



int checkCloseMatches (int MasterCode[], int guess[], int closeMatch )
{
int k;
int j;
for(k=0; k<4; k++){

for (j=0; j<4; j++) {


if (MasterCode[k] == guess[j]){
printf("CLOSE Match found \n");
closeMatch ++;
printf( "%d = Guess \n" , guess[ j ]);
printf( "%d = MasterCode \n \n", MasterCode[ k ]);
printf("%d = closeMatch \n \n", closeMatch);

}// end if

if (MasterCode[k] != guess[j])
printf("No CLOSE match \n");


}//end nested for loop
}//end for loop

return closeMatch;
} // end checkCloseMatches

最佳答案

获取函数的返回值其实很简单,基本上和给变量赋值是一样的。在您的情况下,语法将是这样的:

int result = checkExactMatches(MasterCode, guess, exactMatch);

result 现在将保存函数返回的值。

关于c - C 中的返回值函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com