c - 给定用户一个 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 键。
解决方案
你有两个问题:
- 你
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 $
推荐阅读
- python - 嵌套python列表和字典问题的问题
- python - Beautifulsoup 查找元素
- c++ - 关于在 C++ 中使用 { } 初始化向量
- c - 如何让 fread() 从内存中读取数据?
- c++ - 排序 an 在用户定义的函数中产生问题
- android - 将使用 SHA-1 密钥的 android 项目转移到另一台电脑
- python - Python Selenium - 获取具有日期角色名的元素
- jenkins-pipeline - 在 Jenkins 中将 DSL 作业转换为管道
- laravel - 带有两个参数的 URL
- python - Python“graphics.py”库工作,但没有方法 .yUp()