【发布时间】:2017-05-10 08:37:35
【问题描述】:
我正在做一个关于猜数字的小游戏的简单例子。
我想构建一个检查数字并生成两个值的函数,如下所示:
1) hits - 两个数字中包含的位数以及两个数字在同一位置的位数。
2) 遗漏 - 两个数字都包含但不在同一位置的数字的个数。
例如:
int systemNumber=1653;
int userGuess=5243;
在此示例中,两个数字中都有数字 5 和 3。在两个数字中,数字 3 在同一个位置。但是,systemNumber 中的数字 5 与 userNumber 不在同一个位置。所以,我们这里有 1 次命中和 1 次未命中。
我已经用数组为其编写了代码,我想知道是否有一种方法可以在没有数组和字符串的情况下做到这一点。
这是我的代码。请,如果您对我的代码有任何改进,我想知道它:)
#include <stdio.h>
#include <stdlib.h>
void checkUserCode(int num1[4], int num2[4]); // declare the function which check the guess
int hits=0, misses=0; // hits and misses in the guess
int main(void)
{
int userCode=0;
int userCodeArray[4];
int systemCodeArray[4]={1, 4, 6, 3};
int i=0;
// printing description
printf("welcome to the guessing game!\n");
printf("your goal is to guess what is the number of the system!\n");
printf("the number have 4 digits. Each digit can be between 1 to 6\nGood Luck!\n");
// input of user guess
printf("enter number: ");
scanf("%d", &userCode);
for (i=3; i>=0; i--)
{
userCodeArray[i]=userCode%10;
userCode=userCode/10;
}
checkUserCode(systemCodeArray, userCodeArray);
printf("there are %d hits and %d misess", hits, misses); // output
return 0;
}
/*
this function gets two arrays and check its elements
input (parameters): the two arrays (codes) to check
output (returning): number of hits and misses
if the element in one array also contains in the other array but not the same index: add a miss
if the element in one array also contains in the other array and they have the same index: add a hits
*/
void checkUserCode(int num1[4], int num2[4])
{
int i=0, j=0;
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
if(num1[i]==num2[j])
{
if (j==i)
hits++;
else
misses++;
}
}
}
}
【问题讨论】:
-
如果代码正常工作,请考虑codereview.stackexchange.com。否则,除了改进,您还有什么问题吗?