C Output Question
Using:
printf("%f\n", 4.3) I get a result like 4.300000. Is there any way to automatically realise that it should be 4.3, and print that? Hopefully quite a fast way. I know that it can be done with many sprintfs, and looking through the strings and working out where the zero's start, and then using those strings instead, but I was hoping there would be an easier way. |
you can do this simply with changing:
printf("%f\n", 4.3); to printf("%1f\n", 4.3) |
That doesn't seem to make any difference.
|
sorry i have forgotten a small dot:
printf("%.1f\n", 4.3) the devil is in the detail der teufel steckt im detail |
That appears to round it to 1 decimal place, so 4 is printed as 4.0, and 4.32 is printed as 4.3 - I need a way which will automatically cut off any excess 0's, so 4 would be 4, 4.3 would be 4.3 and 4.32 would be 4.32. Thank you.
|
Code:
#include <stdio.h> Quote:
|
I should read my program's output more carefully. Here's a fixed round() function that does what you need it to:
Code:
char *round(double num) Quote:
|
I get undefined reference to _snprintf when doing this... This normally means that I'm not compiling with the right libraries - which ones do I need (I'm using DJGPP under windows)?
Also - I'll fix these myself if there's a problem - does 4 print 4 or 4.0? does 4.302 print right? |
4 works, but 4.302 doesn't. DJGPP might not have snprintf() because it should be in the standard C library. You can just use sprintf() since %f won't show over 100 characters anyway.
One last try here: Code:
#include <stdio.h> Quote:
|
It seems that now, whenever I output two rounded figures in short succession, the second number is equal to the first... here is the relevant part of the code I am using:
Code:
typedef struct complex { Code:
store 4 5 NB: I have changed the round function so that it outputs 4 instead of 4.0 (changed an i++ to i--) |
It's because round() is using a static buffer. The problem could be fixed with dynamic memory allocation, but the calling function would have to remember to free the memory. As it is now you just have to seperate calls to round() into different statements.
|
thats really really annoying... if i take away the static, would my memory just fill up with a new 100 char string every time i run round? how would i go about clearing them?
|
printf ("%g\n", 4.302): 4.302
printf ("%g\n", 4.30200000): 4.302 printf ("%g\n", 4.0): 4 Should do the trick. |
perfect - that's exactly what i was looking for!
|
All times are GMT -5. The time now is 01:05 PM. |