Nan error

Dec 16, 2016 at 2:55pm
Hello, this is my first topic here. I start lesson c++ with a book, and i find this exercie:
Write from keyboard a program who read a real numer x, and show on monitor the result of:
Here: http://i.imgur.com/TkIk1le.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <math.h>
using namespace std;
float a,b,x,f;
int main()
{
    cout<<"Dati x= "; cin>>x;
    if(a<=10)
    {
        f=sqrt(2-x*x);
    }
    if(a>10)
    {
        f=-2*x/3+1/3;
    }
    cout<<"f(x)= "; cout<<f;
} 


This was my try, but dosen't work, it show like that:
Error Here: http://i.imgur.com/D2QXWbN.png
Last edited on Dec 16, 2016 at 3:14pm
Dec 16, 2016 at 3:28pm
I don't see that the variable 'a' is assigned a value before the code tries to compare it to 10 in the if statements. But if I'm reading the exercise correctly, it looks like it should be looking at the value of x.

I think also that there are vertical lines in the formula in the image around the value under the square root, meaning the absolute value should be used. Otherwise the code may be trying to take the square root of a negative number, which could result in the NAN (not a number) response.
Dec 16, 2016 at 5:00pm
Yes, i confused x wtf a, thank you !


Dec 16, 2016 at 5:06pm
its bad programming to make your variable global
always give a value to variable so no garbage value go in this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <math.h>
using namespace std;
float a,b,x,f; // global variable  
int main()
{
    //float a,b,x,f;  local variable
    cout<<"Dati x= "; cin>>x; // not 'x' a
    if(a<=10) // x<=10
    {
        f=sqrt(2-x*x);
    }
    if(a>10) //x>10
    {
        f=-2*x/3+1/3;
    }
    cout<<"f(x)= "; cout<<f;
} 
Last edited on Dec 16, 2016 at 5:08pm
Dec 16, 2016 at 5:18pm
a should be zero - variables in the global scope are default-initialised

But what is the value of 2-x*x? If it is negative, the sqrt function will fail.
Dec 17, 2016 at 8:24am
Thank you guys, i will learn about local and global variables in the next chapters.

@Chervil, yes, if the value of 2-x*x is negative, the sqrt function will fail, but this is the exercice.

You can close the topic.
Topic archived. No new replies allowed.