samedi 5 décembre 2015

Determine the number of strikes in a random number, depending on user's input

The function "strike" has to return the number of times that the user's input are equivalent.

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.

I'm getting wrong output in strike1. Any ideas how to solve it? (I don't want to solve it with arrays)

#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;
    int temp = num1;
    for (i = 0;i < 4;i++)
    {
            chosenNum1 %= 10;
            if ((temp % 10 == chosenNum1) || (temp % 100 == chosenNum1) || (temp % 1000 == chosenNum1) || (temp % 10000 == chosenNum1))
                strike1++;
            chosenNum1 /= 10;
    }
    return strike1;
}




Aucun commentaire:

Enregistrer un commentaire