-1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 7
    %o is octals, use %d for integers – Jens Munk Aug 09 '15 at 20:17
  • In any case it's better to work with `int cents` and stay away from `float dollars` entirely. You'll get rounding errors due to inexact `float` representation. – Weather Vane Aug 09 '15 at 20:23
  • Thanks @JensMunk for the answer and everyone else for their comments. I had read that the "d" placeholder might print a "+" sign since it's signed decimal integer and for some odd reason chose to go with "o" as it didn't mention this feature. Silly mistake on my part. On another note, I don't seem to be able to chose any of your comments as an appropriate answer. Is it because these are comments and not replies/answers ? – Marc Turpin Aug 09 '15 at 20:33
  • @MarcTurpin Yes, that's why. I didn't bother making an answer – Jens Munk Aug 09 '15 at 20:36
  • 1
    This is a homework question and -1 for not even looking up some `printf()` manual page, which would have been very easy just using google. –  Aug 09 '15 at 20:48
  • 'some odd reason chose to go with "o" ' ; picking random tokens doesn't really work that well when developing software:( – Martin James Aug 09 '15 at 20:51
  • 2
    The plain `%d` format conversion will not place a `+` sign in front of the number; you'd need to use the `+` flag to get that: `%+d`. – Jonathan Leffler Aug 09 '15 at 21:06
  • Alos: Rather than `while(changeOwed < 0.00){`, suggest `while(roundf(changeOwed*100) < 0.00) {` – chux - Reinstate Monica Aug 09 '15 at 21:19
  • @JonathanLeffler thanks for the answer – Marc Turpin Aug 10 '15 at 23:51

1 Answers1

3

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/

paulsm4
  • 114,292
  • 17
  • 138
  • 190