gpt4 book ai didi

c - 递归并打印结果

转载 作者:行者123 更新时间:2023-11-30 16:53:14 25 4
gpt4 key购买 nike

我的任务是抽取一个随机数作为彩票。然后我需要猜测它是什么数字。这个猜测的操作需要进行100次。我不知道我的程序是否运行良好,因为每次我在屏幕上打印机会时,它都会在每一步中给我正确的答案。我有全局声明的步骤变量,所以可能这就是为什么它总是相同的。但是机会呢?

#include<stdio.h>
#include<time.h>

int fchance(int min, int max, int ticket);
int steps = 0;
int main(void) {
int ticket, chance;
int i;
int stepsInTry = 0;
int stepsAverage;
srand(time(NULL));
// rand() % (max - min) + min;
for (i = 0; i < 100; i++) {
ticket = rand() % 100 + 1;
printf("Your ticket: %d ", ticket);
steps = 1;
chance = rand() % 100 + 1;
printf("\nChance: %d", chance);
while (ticket != chance) {
if (chance < ticket) {
chance = ftraf(chance, 100, ticket);
printf("\nChance: %d, step: %d", chance, steps);
}
if (chance > ticket) {
chance = ftraf(1, chance, ticket);
printf("\nChance: %d, step: %d", chance, steps);
}
}
printf("\nOperation nr: %d - number of steps: %d \n", i+1, steps);
stepsInTry += steps;
system("PAUSE");
}

stepsAverage = stepsInTry / 100;
printf("\n\nAverage of steps: %d ", stepsAverage);
system("PAUSE");
return 0;
}

int fchance(int min, int max, int ticket) {
steps++;
int chance;
chance = rand() % (max - min) + min;

if (chance < ticket) {
chance = fchance(chance, 100, ticket);
printf("\nChance: %d, step: %d", chance, steps);
}
if (chance > ticket) {
chance = fchance(1, chance, ticket);
printf("\nChance: %d, step: %d", chance, steps);
}
return chance;
}

输出示例:

Your ticket: 65
Chance: 38
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Chance: 65, step: 11
Operation nr: - numbers of steps: 11

@编辑

对于代码中的困惑,我们深表歉意。将变量名称从我的母语更改为英语。

最佳答案

您的 fchance 函数在打印任何内容之前查找 ticket 的值。我建议将 printf 语句移至 chance = rand()... 语句之后。 – 测试版

关于c - 递归并打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com