c - 根据用户的输入确定随机数的打击次数

标签 c function random

函数“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/

相关文章:

java - 用随机字符填充字符串长度

c - "Segmentation fault 11"for 循环崩溃

c - 重新分配的安全方法

Javascript语法函数问题

java - 作业挑战研究,随机生成的字符串+数字比较

c# - 枚举 DLL 函数?

函数的常量指针参数

c - 在c中处理链表

python - print(1 >> (10 ^ 0xAAAA)) 是0。但是在c语言中是不一样的

c - gcc 4.8.2/ld 2.24 链接失败,gcc 4.4.7/ld 2.20 链接成功