In: Computer Science
#include <stdio.h>
int main(void) {
float funds = 1.0, cost = 0.1;
int candies = 0;
while(cost <= funds) {
candies += 1;
funds -= cost;
cost += 0.1;
}
printf("%d candies with $%.2f left over.\n",candies,funds);
return 0;
}
When you compile and run this code you get 3 candies with $0.40 left over.
Without knowing how floating point numbers work in a computer, would this result be expected? Explain why or why not. Explain why this result, in fact, occurred.
In the computer system, the floating-point number is represented by using IEEE floating-point representation.
The float data type in Programming Language C is stored in the computer system by using IEEE single-precision floating-point representation as given below:
In single precision representation, 1 bit is used as a sign bit, 8 bits are used for the exponent, and 23 bits are used for the mantissa, and X-127 code is used.
The sign bit is stored in a single bit.
0 -> Positive
1 -> Negative
Yes the given output is expected by the given source code.
The statement by statement explanation of the given source code is given below:
#include <stdio.h>
int main(void)
{
//float type variable declaration and initialization
float funds = 1.0, cost = 0.1;
//integer type variable declaration and initialization
int candies = 0;
//while loop
while(cost <= funds)
{
//increment the candies by one
candies += 1;
//decrement the funds by cost value
funds -= cost;
//increment the cost by 0.1
cost += 0.1;
}
//display the value of candies and funds on the computer
screen
printf("%d candies with $%.2f left over.\n",candies,funds);
return 0;
}
OUTPUT:
3 candies with $0.40 left over.
The while() loop will execute for three times.
The value of all three variable in each of the iteration will be:
Iteration 1:
candies = 1
funds = 0.90
cost = 0.20
Iteration 2:
candies = 2
funds = 0.70
cost = 0.30
Iteration 3:
candies = 3
funds = 0.40
cost = 0.40