Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>  
float fahrenheit;
void temperature_convertor(float Fahrenheit)
{
	float C = Fahrenheit - 32;
    float Ce = C * 5;
    float Celsius =  Ce/9;
    float Kelvin =  Celsius + 273.15f;
    printf("Fahrenheit Celsius Kelvin \n %f %f %f", Fahrenheit, Celsius, Kelvin);
}


My code looks like this, and its supposed to output temperature values. But I want it to output an int for fahrenheit and only two decimal places for celsius and kelvin. How can I accomplish this?

What I have tried:

I've tried changing floats to ints and doubles, but it shows errors unless every single value I define is a float.
Posted
Updated 27-Sep-21 2:56am

Add format specifiers to the printf format: printf - C++ Reference[^]
Try this:
C+
printf("Fahrenheit Celsius Kelvin \n %0.0f %0.2f %0.1f\n", Fahrenheit, Celsius, Kelvin);
 
Share this answer
 
You control the number of digits by using the format specifications in the printf statement. See Format Specification Syntax: printf and wprintf Functions | Microsoft Docs[^].
So for two digit precision you use %.2f. To print the Celsius as an integer, you need to cast the value to an integer and use the %d specification.
C++
printf("Celsius: %d\n", (int)Celsius);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900