how do I add function to find the two highest numbers from user input in this code? I will need then to add subtract, multiply and divide the two highest numbers.
#include <iostream>
void sortNum(int& num1, int& num2, int& num3);
int main()
{
int firstNum, secondNum, thirdNum;
std::cout << "Enter first number: ";
std::cin >> firstNum;
std::cout << "Enter second number: ";
std::cin >> secondNum;
std::cout << "Enter third number: ";
std::cin >> thirdNum;
std::cout << "Numbers not in order: " << firstNum << ' ' << secondNum << ' ' << thirdNum << '\n';
A function to sort three integers in order could be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void sortNum(int& num1, int& num2, int& num3)
{
int max = std::max(std::max(num1,num2),num3); //The maximum value
int min = std::min(std::min(num1,num2),num3); //The minimum value
int medium;
if(num1 != max && num1 != min) //The other value
medium = num1;
elseif(num2 != max && num2 != min)
medium = num2;
else
medium = num3;
//And store the results
num1 = max;
num2 = medium;
num3 = min;
}
This isn't an efficient implementation, but it should work.
From you code , i interfiere you want to have a minimum element at num1 (not at num3)
You can also do it like this :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void sortNum(int& num1, int& num2, int& num3)
{
auto swap = [] (int& numA, int& numB) { int temp=numA; numA=numB;numB=temp;};
if (num1>num2) {
if (num1>num3) {
if(num2>num3) swap(num1,num3);
else { swap(num1,num2); swap(num2,num3);}
}
else swap(num1,num2);
}
else {
if (num2>num3) {
if (num1<num3) swap(num2,num3);
else { swap(num1,num3); swap(num2,num3);}
}
}
I think, using lambda function in C++11 would be same fast, it would insert inline.
But, if you not want to use it, then simply substitue each swap by
int temp=numA; numA=numB;numB=temp;
I believe you search a quick algorithm,
This code would give you less swaps.
greatings, Daniel
Yes ! This would be better, because i am sure that g++ will be optimized for integer swap.
It is possible that a integer swap between 2 directions can be done in one ensambler instruction ?
greatings, Daniel
Solution of "cire" i believe is the most good looking and easier. However always use 3 swaps.
Solution which i (danjiun) give, it do in 0,1 or 2 swaps, but is not so good looking.
I have another idea :
If we know limits about this numbers, for example, have a minimum and a maximum value, and this range is not too big, and we want to use many many times this function, you can also "precalculate" results, and assign quicker.
Daniel
sorry guys, I'm at the very beginning with c++! I don't seem to understand how to add the output sum, difference, product and division of the two highest input numbers. any help?