-1

Why is k value returns 0? Please help.

double fah, kel;

fah = std::atof(input.c_str());  //convert string input to a double & assign value to be fah degree 
kel = (double)((f + 459.67) * (5/9)); //calculate fah temp to kelvin 

k value returns 0 when I add "5/9" to the calculation.

user2925557
  • 85
  • 1
  • 3
  • 7

4 Answers4

4

In C++, 5/9 == 0 because of integer division.

Use 5.0/9.

Matt
  • 20,108
  • 1
  • 57
  • 70
2

The problem is integer division. The result of this:

5/9

is 0. You should use a floating point type:

5/9.0 // 9.0 is a double.
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Why is only one of those two number needs to be in a decimal form? – user2925557 Nov 27 '13 at 20:19
  • 1
    @user2925557 it is enough for one of the operands of the division operator `/` to be a floating point (FP) type for the operation to be calculated in FP (and the result of the operation to be FP) – juanchopanza Nov 27 '13 at 20:23
  • @user2925557 an operation of `int/double` or `double/int` is automatically promoted to a `double` result. For readability, it is often good to write both as a double - though, that is not required. – Zac Howland Nov 27 '13 at 20:25
0

Expression 5 / 9 has integral type that is its result is equal to 0. Change (5/9) at least to (5.0/9)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

This is an integer division issue. Additionally, you simplify the equation a bit:

Dk = C*Df + C*B ===> Dk = C*Df + A

where Dk is degrees Kelvin, Df is degrees Farenheit, C is the 5/9 constant, and A is C*Kelvin Offset (also constant). Which would make your code:

const double FtoKMultiplier = 5.0/9.0; // done at compile time
const double FtoKOffset = 459.67 * FtoKMultiplier; // also done at compile time
double fah = std::atof(input.c_str());
double kel = FtoKMultipler * fah + FtoKOffset; // single multiplication and addition at runtime
Zac Howland
  • 15,777
  • 1
  • 26
  • 42