This is my print statement:
printf("%d %f\n",kPower, raisePower);
This is my output:
-4 0.000100
-3 0.001000
-2 0.010000
-1 0.100000
0 1.000000
1 10.000000
2 100.000000
3 1000.000000
4 10000.000000
I want it to be printed like this:
UPDATE
So I made my positive values line up:
-4 0.0
-3 0.0
-2 0.0
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
This is my new code so far:
printf("%d %10.1f\n",kPower, raisePower);
I don't know, should I make a for loop to print each one (positive results vs negative result) in a different format?
2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.
You can use decimal data types to represent large numbers accurately, especially in business and commercial applications for financial calculations. You can pass decimal arguments in function calls and in define macros.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
#include <stdio.h>
char *get_number_formatted(double f)
{
static char buf[128]; // this function is not thread-safe
int i, j;
i = snprintf(buf, 128, "%20.10f", f) - 2;
for (j = i - 8; i > j; --i)
if (buf[i] != '0')
break;
buf[i + 1] = '\0';
return buf;
}
int main(void)
{
int i;
for (i = -4; i < 5; ++i)
printf("%5d %s\n", i, get_number_formatted(pow(10.0, i)));
return 0;
}
http://ideone.com/KBiSu0
Output:
-4 0.0001
-3 0.001
-2 0.01
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
printf()
cannot print a variating length of decimal digits, so basically what I did was print the formatted number into a buffer and then cut the exceeding zeros.
Try calculating the powers first using pow()
from math.h
and then:
You can use %10f to precede the number with blanks in the example total of 10 spaces:
printf ("Preceding with blanks: %10f \n", 10000.01);
Source: cplusplus.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With