首页 > 解决方案 > 给定用户一个 3 位数字,找到并打印它的最小数字

问题描述

我尝试了一个 C 程序,它从用户那里获取一个 3 位整数,然后找到并打印它的最小数字。

#include <stdio.h>
int main()
{
    int a,b,c;
    printf("Enter a 3-digit integer : ");
    scanf("%d%d%d",&a,&b,&c);
    if(a<b){
        if(a<c){
            printf("%d is the minimum digit\n",a);
        }
        else printf("%d is the minimum digit\n",c);
    }
    else {
        if (b<c){
            printf("%d is the minimum digit\n",b);
        }
    }

    return 0;
}

但这不是正确的方法,因为每次我需要在输入 3 位数字时按 Enter 键。

标签: cif-statementnested

解决方案


你有两个问题:

  • scanf("%d%d%d",&a,&b,&c);读的是 3 个数字,而不是 3 个数字。
  • 如果数字是例如 321,那么你什么也不打印,因为没有else用于测试if(b<c)

要读取 3 位数字,您可以这样做scanf("%1d%1d%1d",&a,&b,&c);,但读取的数字可以将其数字分开。

一种方法可以是:

#include <stdio.h>
#include <ctype.h>

int main()
{
    unsigned char a,b,c;
    printf("Enter a 3-digit integer : ");
    if ((scanf("%c%c%c",&a,&b,&c) == 3) &&
        isdigit(a) &&
        isdigit(b) && 
        isdigit(c))
      printf("%d is the minimum digit\n",
             ((a < b) ? ((a < c) ? a : c)
                      : ((b < c) ? b : c))
             - '0');
    else
      puts("invalid values");

    return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall n.c
pi@raspberrypi:/tmp $ ./a.out
Enter a 3-digit integer : 123
1 is the minimum digit
pi@raspberrypi:/tmp $ ./a.out
Enter a 3-digit integer : 321
1 is the minimum digit
pi@raspberrypi:/tmp $ ./a.out
Enter a 3-digit integer : 213
1 is the minimum digit
pi@raspberrypi:/tmp $ ./a.out
Enter a 3-digit integer : 1ae
invalid values
pi@raspberrypi:/tmp $ 

推荐阅读