【问题标题】:Show the smallest digit from three digits in C++在 C++ 中显示三位数字中的最小数字
【发布时间】:2015-11-01 01:20:01
【问题描述】:

我想制作一个程序,让用户输入由空格分隔的三位数字,我想显示最小的数字。

查看我的代码:

#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

它不显示最小的数字。我的代码有什么问题,我该如何解决我的问题?

【问题讨论】:

  • 你需要调试你的代码

标签: c++ visual-studio min


【解决方案1】:

结果应该用零初始化

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;   
}

【讨论】:

    【解决方案2】:

    这里有一个隐藏的假设,即 abc 是积极的。如果你允许这样的假设,你就快到了——你只需要将result 初始化为0 而不是1

    【讨论】:

      【解决方案3】:

      提示:

      在编写 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;
      }
      

      很多痛苦,它会预防。更高的生产力,它会产生。

      ;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        • 2011-04-24
        • 1970-01-01
        • 2016-06-01
        • 2020-03-21
        • 2010-11-21
        • 1970-01-01
        相关资源
        最近更新 更多