Search code examples
ccastingcs50floating-point-conversion

c float to int conversion acting weird


I'm trying to convert a float value to an int in C. I'm using print statements to see what's happening and making sure I'm getting the desired results, but something is not working correctly. Here is my code:

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

int main(void){

float changeOwed = -1.00;

while(changeOwed < 0.00){
    printf("How much change is owed?\n");
    changeOwed = GetFloat();
    }

printf("%f\n", changeOwed);

int centsOwed = roundf(changeOwed*100);
printf("%o\n", centsOwed);

If user input is, lets say 0.49, here is the output:

0.490000
61

I don't understand why the cast result is 61. I would expect normal errors to be a result of 0, 48 or 50, but I don't get this weird result and can't figure out the logic of it.


Solution

  • In case you don't get it yet ...

    "061" is octal for "49".

    Use printf("%d") instead of "%o" if you want to see a decimal "49".

    Here is a good list of "printf" format options:

    http://www.cplusplus.com/reference/cstdio/printf/