Now, write a program to calculate and print the maximum and minimum signed and m
ID: 3873575 • Letter: N
Question
Now, write a program to calculate and print the maximum and minimum signed and maximum unsigned number stored in 1 byte. Think about the equation to determine how many numbers can be represented in 8 bits with two possible choices for each bit. How are you going to take the exponent? You could multiply 2 by itself 8 times or you can use a built-in function, pow(base, exp), from the cmath library. For example:
#include
#include using namespace std;
int main()
{ cout
<< “2^3 is: “ << pow(2,3) << endl;
return 0;
}
Explanation / Answer
The formulas for a signed number with N bits (using two's complement) are:
min = -1 * 2^(N - 1)
max = 2^(N - 1) - 1
The formulas for an unsigned number with N bits are
min = 0
max = 2^N - 1
1 byte has 8 bits. So for our case N = 8.
The c++ program is as follows:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// 1 byte has size equal to 8 bits
int SIZE = 8;
// calulate maximum for signed number
int bytemax_calculate;
bytemax_calculate = (pow(2, SIZE-1) -1);
// calculate minimum for signed number
int bytemin_calculate;
bytemin_calculate = -1 * pow(2, SIZE-1);
// calculate maximum for unsigned number
int byteunsigned_calculate;
byteunsigned_calculate = pow(2, SIZE)-1;
// Print result
cout << "Maxmimum byte (signed): "<< bytemax_calculate << endl;
cout << "Minimum byte (signed): "<<bytemin_calculate << endl;
cout << "Maximum byte (unsigned): " << byteunsigned_calculate << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.