I have to printfs in a loop an I want to print the output in two lines, instead of intermingled on one line.
Like this:
printf("| %-7.2f ", Fahrenheit);
which produces:
| -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 |
When I add printf("| %-6d", Celsius);
under the printf above, it prints right next to/in the middle of my first printf.
I want the output to be like:
| -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 |
| -300 | -275 | -250 | -225 | -200 | -175 | -150 | -125|
instead of the two sets of values being intermingled on the same line.
part of my code:
for(Celsius = CelsiusMin;Celsius <= CelsiusMax; Celsius += CelsiusStep)
{
Fahrenheit = FahrenheitZero + Celsius * CelsiusToFahrenheit;
printf("| %-7.2f ", Fahrenheit);
printf("| %-6d", Celsius);
}
return EXIT_SUCCESS;
}
You can't directly have one sequence of printf()
statements writing to line 1 and a second concurrent sequence of printf()
statements writing to line 2, so you're going to have to fake it.
You probably need something that builds up the two lines of output, and then prints them when they're ready:
char line1[128];
char line2[128];
char *next1 = line1;
char *next2 = line2;
for (int c = -325; c <= -125; c += 25)
{
double f = (c + 40.0) * (9.0 / 5.0) - 40.0;
next1 += sprintf(next1, "| %-7.2f ", f);
next2 += sprintf(next2, "| %-7d ", c);
}
printf("%s|\n", line1);
printf("%s|\n", line2);
Sample output:
| -553.00 | -508.00 | -463.00 | -418.00 | -373.00 | -328.00 | -283.00 | -238.00 | -193.00 |
| -325 | -300 | -275 | -250 | -225 | -200 | -175 | -150 | -125 |
The conversion formula is simpler than the usual one you see quoted, and is symmetric for converting °F to °C or vice versa, the difference being the conversion factor (9.0 / 5.0)
vs (5.0 / 9.0)
. It relies on -40°C = -40°F. Try it:
C = 0°C; (C+40) = 40; (C+40)*9 = 360; (C+40)*9/5 = 72; (C+40)*9/5-40 = 32°F
.
F = 32°F; (F+40) = 72; (F+40)*5 = 360; (F+40)*5/9 = 40; (F+40)*5/9-40 = 0°C
.
You might do better with the degrees Celsius as printed as a double
too; I kept the integer representation you chose, but made sure the numbers line up on the two lines.
FYI: Absolute zero is -273.15°C, 0K, -459.57°F. So you're attempting to print non-existent temperatures.