显示c++中三位数中最小的一位

Show the smallest digit from three digits in C++

本文关键字:一位 c++ 三位数 显示      更新时间:2023-10-16

我想编写一个程序,用户输入以空格分隔的三位数字,我想显示最小的数字。

查看我的代码:

#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, bc是正的。如果您允许这样的假设,您就接近成功了—您只需要将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;
}
多痛苦,它就能预防。生产力越高,它就会生产。