显示c++中三位数中最小的一位
Show the smallest digit from three digits in C++
我想编写一个程序,用户输入以空格分隔的三位数字,我想显示最小的数字。
查看我的代码:
#include<iostream>
using namespace std;
int main( )
{
int a,b,c;
cout<<" enter three numbers separated by space... "<<endl;
cin>>a>>b>>c;
int result=1;
while(a && b && c){
result++;
a--; b--; c--;
}
cout<<" minimum number is "<<result<<endl;
system("pause");
return 0;
}
样本输入:3 7 1
样本输出:2它没有显示最小的数字。我的代码中的问题是什么,我如何解决我的问题?
结果初始化为0
int result = 0;
然而,这种方法是错误的,因为用户可以输入负值。
程序可以这样写
#include <iostream>
#include <algorithm>
int main( )
{
std::cout << "Enter three numbers separated by spaces: ";
int a, b, c;
std::cin >> a >> b >> c;
std::cout << "The minimum number is " << std::min( { a, b, c } ) << std::endl;
return 0;
}
这里有一个隐藏的假设,即a
, b
和c
是正的。如果您允许这样的假设,您就接近成功了—您只需要将result
初始化为0
而不是1
。
提示:
在编写c++时,总是倾向于使用标准库中精心为您提供的算法来编写代码。
#include <iostream>
#include <algorithm>
using namespace std;
int main( )
{
int a,b,c;
cout<<" enter three numbers separated by space... "<<endl;
cin>>a>>b>>c;
int result = std::min(a, std::min(b, c));
cout<<" minimum number is " << result<<endl;
system("pause");
return 0;
}
多痛苦,它就能预防。生产力越高,它就会生产。
。
相关文章:
- 一位朋友将模板函数缩写为clang和gcc
- 斐波那契数列部分和的最后一位数字
- 将第 n 个斐波那契数的大斐波那契数的最后一位编程.C++
- 如何检查 int 中是否恰好设置了一位?
- 如何找到由公式计算的非常大的数字的最后一位数字?
- 我如何使用十一位数字
- 使用位操作将8字节数字中的每个字节中的一位转换为单个字节
- 我在spoj-lastdig2中使用我的代码 - 重新访问的最后一位数字
- 查找非常大的 2^n 数字的最后一位数字
- 如何计算具有相同SHA-160和的另一位模式
- C++ 仅输出一个小数点后一位
- 如何将用户输入的最小值限制为流大小减去一位
- 如何为一次只写一位的程序编写测试程序
- 减去2个数字的每一位
- 找到一个提升到一定幂的数字的最后一位
- 如何在c++中交换数字的第一位和最后一位
- 根据c++社区中一位知识渊博的作者的说法,下面显示的代码应该无法编译.他错了吗?
- 将浮点数四舍五入到小数点后一位,然后转换为字符串
- 指数的最后一位——答案错误
- 显示c++中三位数中最小的一位