Reputation:
I want to make a program in which user enter the three digits separated by the space and i want to show the smallest digit.
See my code:
#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;
}
Sample input:
3 7 1
Sample output:
2
It doesn't show the smallest digit. What's the problem in my code and how can I solve my problem?
Upvotes: 2
Views: 555
Reputation: 69902
hint:
When writing c++ always prefer to write code in terms of the algorithms that have been thoughtfully provided for you in the standard library.
#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;
}
Much pain, it will prevent. More productivity, it will produce.
;)
Upvotes: 2
Reputation: 311068
The result should be initialized by zero
int result = 0;
nevertheless the approach is wrong because the user can enter negative values.
The program could be written the following way
#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;
}
Upvotes: 4
Reputation: 311853
There's a hidden assumption here that a
, b
and c
are positive. If you allow for such assumption, you're nearly there - you just need to initialize result
to 0
instead of 1
.
Upvotes: 3