C++ Problem I get “nan” as output everytime I run my program

  • A+
Category:Languages

I was required to create a program with a function that changes height in feet to height in meters. I made the function and when I cout from the function I get the right value but when I cout it in main I get "nan". I dont understand why the value is not printing. This is my first time using this website so I am sorry if I miss anything.

#include <iostream> #include <iomanip> #include <cmath>  using namespace std;   double heightInMeters(double feet , double inches) { double footToMeter = 0.305; double inchToMeter = 0.0254;  double heightInMeters = ((footToMeter * feet) + (inchToMeter * inches)); cout << heightInMeters << endl; }   int main() {  double feet, inches, calcheight; char ch;  cout << "Enter your height [Use format ft-in]: "; cin >> feet >> ch >> inches;  calcheight = heightInMeters(feet, inches); cout << calcheight << endl;  return 0; } 

 


This function here:

double heightInMeters(double feet , double inches) {    double footToMeter = 0.305;    double inchToMeter = 0.0254;     double heightInMeters = ((footToMeter * feet) + (inchToMeter * inches));    cout << heightInMeters << endl; } 

isn't returning anything. That's undefined behavior, what you get here

calcheight = heightInMeters(feet, inches); 

Is most likely just some invalid rubbish value then. Perhaps instead of this:

cout << heightInMeters << endl; 

You wanted this:

return heightInMeters; 

Does your compiler issue any warnings for your code? If not, please try to find out if you can set it to give you more warnings. Most compilers usually complain about missing returns.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: