函数“strike”必须返回用户输入相等的次数。
Assume, the random number is 1234.
if the user's input has one of the random's numbers, then strike1++.
e.g., if my input is 5152 then strike1 will be 2.
if my input is, 1112, then strike will be again 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;
}
最佳答案
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;
}
关于c - 根据用户的输入确定随机数的打击次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108507/