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 means that the value is going to infinity, which cannot be represented (thus Not a Number). It overflows the double type.
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With