0

I am in a C++ class and for my final I am developing a program that asks a user whether they want to convert Fahrenheit temps to Celsius or Kelvin (there is a third menu option, but it is irrelevant to the issue). One of the tasks is to write a void function to convert to Celsius and to convert to Kelvin. I am also supposed to store the Celsius conversion, the Kelvin conversion, and the Fahrenheit number in an array. I am running into an issue where my floating-point Celsius variable (cel in the program) is always 0. This results in Kelvin always being 273.15. I have checked and "f" is storing the number that I input. Below is my function:

// Celcius function
void showCelcius(float f)
{
    float cel, kel;
    cel = (5/9) * (f - 32);
    cout << cel << endl;                           // Test to check cel value after equation
    kel = cel + 273.15;
    cout << fixed << showpoint << setprecision(1);
    cout << f << " Fahrenheit = "
        << cel << " Celcius\n";
    temps[totalCount][0] = f;
    temps[totalCount][1] = cel;
    temps[totalCount][2] = kel;
}

Here is the ouput:

enter image description here

I have also tried putting the whole equation in parentheses. How can I get the variable "cel" to evaluate to the result of the equation?

TheCanary
  • 21
  • 1
  • Replace `5/9` (which is 0, since it uses integer division) by `5.f/9`. Then find a guide on types and type conversion in C++. – chtz Aug 07 '22 at 21:04

1 Answers1

0

I figured it out. It appears that since '5' and '9' were of type int it was not evaluating the equation at all. I added static_cast() to each number and it works.

// Celcius function
void showCelcius(float f)
{
    float cel, kel;
    cel = (static_cast<float>(5)/static_cast<float>(9))*(f - static_cast<float>(32));
    cout << cel << endl;
    kel = cel + 273.15;
    cout << fixed << showpoint << setprecision(1);
    cout << f << " Fahrenheit = "
        << cel << " Celcius\n";
    temps[totalCount][0] = f;
    temps[totalCount][1] = cel;
    temps[totalCount][2] = kel;
}
TheCanary
  • 21
  • 1
  • that's a very verbose way of saying the same thing as @chtz's comment. might be worth reading https://en.cppreference.com/w/cpp/language/implicit_conversion, specifically the sections on Numeric Promotion and Conversion – Sam Mason Aug 08 '22 at 14:15