Given two integers, say a and b, the maximum and minimum can be determined with the following formulas:
max〖= (a+b+ |a-b|)/2〗, min〖= (a+b-|a-b|)/2〗
I'm writing a C++ program that will prompt for and accept two integer values via the keyboard.
The first of these values should be stored in variable a and the second in b. The program should then compute the max and min of a and b using the above formulas. The values of a, b, max, and min should be displayed on the screen with descriptive literals. I need to use the cmath header and the abs() function for calculating the absolute value (| |). How do I declare the formulas? I looked it up but all I see is arrays and I can't use that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream> // cout
#include <cmath> // abs
usingnamespace std;
int main()
{
// Variables for a and b
int fmax = 'a'; 'b';
int fmin = 'b'; 'a';
// Formulas for fmax and fmin
fmax = (a + b + abs (a - b)) / 2;
fmin = (a + b - abs (a - b) ) / 2;
cout << "Enter an integer a (positive or negative): \n";
cout << "Enter an integer b (positive or negative): \n";
C++ does not work like Excel; you can't assign the variable a symbolic value or some formula in advance (or at least, if you wanted to do something similar to that, it would take a lot more effort).
Each instruction is done sequentially.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream> // cout
#include <cmath> // abs
usingnamespace std;
int main()
{
int a {};
int b {};
cout << "Enter an integer a (positive or negative): \n";
cin >> a;
cout << "Enter an integer b (positive or negative): \n";
cin >> b;
// Formulas for fmax and fmin
int fmax = (a + b + abs (a - b)) / 2;
int fmin = (a + b - abs (a - b)) / 2;
cout << "Max: " << fmax << ", Min: " << fmin << '\n';
}
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int a, b;
cout << "Enter two whole numbers: ";
cin >> a >> b;
cout << "Max: " << ( a + b + abs( a - b ) ) / 2 << '\n'
<< "Min: " << ( a + b - abs( a - b ) ) / 2 << '\n';
}