猜数:对于1到100间的正整数,给出该数除以3,4和7的余数,猜出这个数是多少。

这是学校的ACM平台上的题目。之前我遇到这个问题,开始不知道怎么设计算法,于是在csdn上找到一篇类似的文章,其代码非常简短,但是算法有点难度,需要一些数学技巧,不太好理解,作者也花了不少篇幅来讲解其算法。
下面是我写的代码,思路很简单,就是利用for循环逐一判断,符合条件就输出,同时使用flag记录一次,如果所有数逐一排查之后flag=0就说明找不到符合条件的数。

题目:
对于1到100间的正整数,给出该数除以3,4和7的余数,猜出这个数是多少。在一行上输入该数除以3,4,7的三个余数。若答案唯一,在一行上输出计算机猜出的整数。若答案不唯一,在一行上输出每个符合这样条件的整数,中间用分号隔开(最后一个整数后面也有分号)。若无符合条件的整数,输出"no solution"。
样例输入
1 0 5
样例输出
40;
代码实现:

#include<stdio.h>
int main()
{
    int t, f, s, i = 1,sum = 0;
    int flag = 0;
    scanf("%d%d%d", &t, &f, &s);
    for (i; i <= 100; i++)
    {
        if (i % 3 == t && i % 4 == f && i % 7 == s)
        {
            printf("%d;", i);
            flag = 1;
        }
        else
        {
            flag = 0;
        }
        sum += flag;
    }
    if (sum == 0)
    {
        printf("no solution");
    }

    return 0;
}

第一次写博客,如果有些许错误,还请谅解。

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的数游戏的 C 语言代码,支持人数计算机和计算机数人两种模式: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> // 计算机数,人 void computer_guess() { srand(time(NULL)); int number = rand() % 100 + 1; printf("I have a number between 1 and 100. Can you guess what it is?\n"); int guess, count = 0; do { printf("Enter your guess: "); scanf("%d", &guess); count++; if (guess > number) { printf("Too high! Try again.\n"); } else if (guess < number) { printf("Too low! Try again.\n"); } } while (guess != number); printf("Congratulations! You guessed the number in %d tries.\n", count); } // 人数,计算机 void human_guess() { printf("Think of a number between 1 and 100, and I'll try to guess it.\n"); int low = 1, high = 100, guess, count = 0; do { guess = (low + high) / 2; printf("Is it %d?\n", guess); printf("Enter '1' if it is too low, '2' if it is too high, or '3' if it is correct: "); int response; scanf("%d", &response); count++; if (response == 1) { low = guess + 1; } else if (response == 2) { high = guess - 1; } } while (guess != number); printf("I guessed the number in %d tries.\n", count); } int main() { printf("Welcome to the number guessing game!\n"); printf("Enter '1' for computer out and human guess, or '2' for human out and computer guess: "); int mode; scanf("%d", &mode); if (mode == 1) { computer_guess(); } else if (mode == 2) { human_guess(); } else { printf("Invalid mode.\n"); } return 0; } ``` 在这个程序中,`computer_guess` 函数实现了计算机数,人的游戏模式,而 `human_guess` 函数实现了人数,计算机的游戏模式。在 `main` 函数中,我们首先让用户选择游戏模式,然后根据选择调用相应的函数。在计算机数,人的游戏模式中,我们使用 `rand` 函数生成一个随机数作为计算机所的数,然后使用一个循环让用户测这个数。在人数,计算机的游戏模式中,我们使用二分查找算法让计算机测用户所的数,并根据用户的反馈调整测的范围,直到中为止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值