I created a small program to convert temperature units from C° to F.
the char unit needs to be reversed 'C' to 'F' and vice versa. in order to do so, I'm modifying the address of char unit
directly in my function temp
.
now I'm a bit confused about how printf works when printing a function directly. precisely at this line:
printf("%.1lf %c", temp(input, &unit), unit);
my problem is that the printf
is printing my unmodified unit
even though my function already modified the value of char unit
: result / expected
I can solve this by storing the function value into a double variable and printing it:
result = temp(input, &unit);
printf("%.1lf %c", result, unit);
could someone explain to me where my above logic is wrong
printf("%.1lf %c", temp(input, &unit), unit);
It seems to me that printf is printing the value of my function first and then the unit
. the unit
value is being modified inside the function so I don't understand why it wasn't modified.
thanks a lot for your time.
#include <stdio.h>
double temp(int, char *);
int main(void) {
int input = 0;
char unit = 'a';
double result = 0.0;
printf("Temperature unit:");
scanf("%d %c", &input, &unit);
printf("%.1lf %c", temp(input, &unit), unit);
}
double temp(int temp, char * unit) {
double output = 0.0;
//convert to C°
if (*unit == 'F') {
output = (((double)temp - 32) * 5 / 9);
*unit = 'C';
}
else if (*unit == 'C') {
output = (double)temp * 9 / 5 + 32;
*unit = 'F';
}
else {
printf("wrong unit");
}
return output;
}