函数“strike”必须返回用户输入等效的次数。
假设,随机数为1234。
如果用户的输入中有一个随机数,则执行strike1 ++。
例如,如果我的输入是5152,那么strike1将是2。如果我输入的是1112,那么将再次点击2.
我在strike1输出错误。任何想法如何解决? (我不想用数组解决它)
解决方案:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int hit(int num);
int strike(int num);
int rndNum(int num);
void main()
{
int num = 0;
int chosenNum;
int saveHits, saveStrikes;
srand(time(NULL));
printf("The Random number: %d", chosenNum = rndNum(num));
printf("\nPlease enter a 4 digit number: ");
scanf("%d", &num);
saveHits = hit(num, chosenNum);
saveStrikes = strike(num, chosenNum);
printf("\nThe number of hits: %d", saveHits);
printf("\nThe number of strikes: %d", saveStrikes);
getch();
}
int rndNum(int num)
{
int rndNum = rand() % 9000 + 1000;
return rndNum;
}
int hit(int num1, int chosenNum1)
{
int i, hit1 = 0;
for (i = 0; i < 4; i++)
{
if (num1 % 10 == chosenNum1 % 10)
hit1++;
num1 /= 10;
chosenNum1 /= 10;
}
return hit1;
}
int strike(int num1, int chosenNum1)
{
int i, strike1 = 0, n = 1;
int temp = num1, temp2 = chosenNum1;
for (i = 0;i < 4;i++)
{
while (n > 0)
{
if (temp > 0)
{
if ((temp % 10 == temp2 % 10))
{
strike1++; n--;
}
else
temp /= 10;
}
else
n--;
}
temp2 /= 10;
n = 1;
temp = num1;
}
return strike1;
}
答案 0 :(得分:1)
"./"