Khizar Muhammad
Khizar Muhammad

Reputation: 93

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

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;
}

Upvotes: 6

Views: 1463

Answers (3)

Rong Wu
Rong Wu

Reputation: 11

void f()
{
    double a=0.3;
    cout << a << endl;
}
//
// inside main function 
f();

double f()
{
    double a=0.3;
    return a;
}

// inside main function 
cout << f() << endl;

Because the return value of your code is not specified, the output is “nan“

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

heightInMeters doesn't have an explicit return value.

Therefore, since it's not a void function (or main), the behaviour of your program is undefined.

Didn't your compiler warn you of that? It's an easy spot for a compiler to make in your case, and the current crop of compilers all warn if you turn the warning level up appropriately.

(Granted, NaN is a peculiar manifestation of that undefined behaviour.)

Finally, note that one foot is exactly 0.3048 meters. Base your conversion metrics from that. Your values introduce unnecessary imprecision.

Upvotes: 3

Blaze
Blaze

Reputation: 16876

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.

Upvotes: 7

Related Questions