c - Float not being converted correctly -


i working on program convert dollars cents. take in user input float using predefined function try multiply float 100 gives me incorrect value. heres code:

printf("change in dollars: "); change= getfloat(); cents= round(change*100); printf("cents %f",cents); 

this logical error because program runs fine there wrong mathematics example if enter 1.50 when prompted, return 1004 wrong. want happen 150 outputted.

this because have locale decimal separator , instead of ., , since not checking return value of scanf() "which books , every tutorial", variable not being initialized , printing consequence of layout of program instead of value inputed user.

to verify say, suggest compiling same program without modification different compilation flags.

what must ensure input correct, try this

float getfloat(int *ok)  {     float value = 0;     if (scanf("%f", &value) != 1)         *ok = 0;     else         *ok = 1;     return value;  } 

which call this

int   result = 0; float change = getfloat(&result); if (result == 0)     return -1; float cents = round(change * 100);  printf("cents %f",cents); 

if decimal separator issue, above program not output anything, because scanf() return 0, , hence ok 0 after call function.

one important consequence of ignoring return value of non-void functions if value not initialized in case scanf(), , don't know because didn't check return value, undefined behavior happen, meaning program contain bugs difficult find , hence hard fix.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -