0

QUESTION: MY CODE BELOW IS NOT GIVING ME THE VALUE OF "i" in the proper format. First it would give me a value of 0. I made some changes. Now, when asked "How much change is owed?" If the input is .45 then the output that comes back is 45.

CODE:

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int q = 25;
int d = 10;
int n = 05;
int p = 01;

int main(void)
{
    float f;

    do 
    {
        printf("Hi. How much change is owed?\n");
        f = GetFloat();
    }
    while (f <= 0); 

    int i = f * 100; //I TOOK AWAY THE * 100 BUT THEN THE OUTPUT BECOMES 0//
    printf("%i", i);

TERMINAL:

Hi. How much change is owed?
.45
45
1

It's printing exactly what it should. When you input .45, the code multiplies it by 100, resulting in 45. That is stored in an integer variable, which you then print out.

When you took away the *100, it still does what it is supposed to do. f is a float, i is an int. If f is .45 an you do i=f;, then the value in f is converted to an int and stored in i. Remember how the conversion process works. It will take the value in float f and will truncate the number, discarding any fractional part, and storing the whole number that remains in the integer. So, if f is anything from 0 to 0.999999999999... , it will store 0 in i.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. Let's keep up on forum maintenance. ;-)

1
  • Thank you Cliff! – Joe Jun 27 '16 at 12:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .