I finally broke down and wrote my first header file, but one of my functions is acting a little weird... This function is supposed to convert from Celsius to Fahrenheit but whenever I call the function, it returns an incorrect value. Is there an easy way to multiply the float by 9/5?

float ctof(float temp)
{
      float fahrenheit = temp;
      fahrenheit = (9/5)*fahrenheit + 32;
      return fahrenheit;
}

Dani AI

Generated

The incorrect output was caused by integer division: the expression with 9/5 is evaluated as an integer ratio (1), so the scale factor became 1 instead of 1.8. As hinted, the fix is to force floating-point arithmetic (for example 9.0f/5.0f or 1.8f). See the usual arithmetic conversions for details: Usual arithmetic conversions.

A safe project layout keeps the prototype in the header and the implementation in a .cpp file. The header can use include guards (or #pragma once) and should expose just the interface. Implementation examples:

/* tempconv.h */

#ifndef TEMPCONV_H
#define TEMPCONV_H

float ctof(float c);   // prototype only

#endif /* TEMPCONV_H */
/* tempconv.cpp */

#include "tempconv.h"

float ctof(float c)
{
    return c * 9.0f / 5.0f + 32.0f;
}

Additional tips: a constexpr or inline conversion factor keeps intent clear (constexpr float R = 9.0f/5.0f;). Putting a function body in a header is acceptable only when it is inline or constexpr (see: inline specifier) to avoid multiple-definition errors. Watch for mixed types elsewhere — if temp or the literals are integers, the integer-division trap reappears. Compiler warnings about implicit conversions are useful; enabling them often catches these mistakes early. After applying the floating-point literal fix, reported the function worked as expected.

Recommended Answers

All 4 Replies

you don't normally put executable code in a header file. All header files contain are function prototypes, classes , structures and macros. Everything else goes in the *.c or *.cpp implementation file.

>> (9/5)*fahrenheit + 32
that is the same as 1 * fahrenheit + 32 because 9/5 = 1 (integer arithmetic discards all fractions)

Thanks I guess I'll have to research more before I proceed.

Start with this thread. Note that it is using floating point arithmetic, not integer arithmetic like you tried to do.

Thanks! I got it to work now so I can continue with my project!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.