0

I have some problem with the fonction sqrt()! I'm quite a beginner so be indulgent please, the answer might be really simple. So here's my code:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int touche;
    int i;
    float x;
    float racx;
    const int NFOIS = 5;
    cout << "Bonjours!" << endl;
    cout << "Je vais vous calculer " << NFOIS << " racines carrees" << endl;
    for (i = 0; i < NFOIS; i++)
    {
        cout << "Donner un nombre: " ;
        cin >> x;
        if (x = 0.0)
        {
            cout << "Le nombre" << x << "ne possede pas de racines carrees!" << endl    ;
        }
        else
        {
            racx = sqrt(x);
            cout << "Le nombre " << x << " a une racine carree de : " << racx << endl;    
        }
    }
    cout << "Programme termine veuillez entrer un charactere pour fermer le programme." << endl;
    cin >> touche;
    return 0;
}

My problem is when i enter a number (it is stored, i checked it with a cout before posting it here "just in case it was it") is when the sqrt(x); it only tell the program that x and racx is 0 no matter what i type. I'm really clueless of what it can be. I also tried to change the #include for "math.h" and still the same thing, so i think my code is wrong somewhere.

I use Visual c++ 2013 if you wanted to know that in windows 7 ultimate 64-bits.

PS: As you can notice my first language is french, but don't worry i understand english very well, even if i'm bad at writting :P.

Anyway, thank you for the attention and help! It will be appreciated!

  • 3
    `x=0.0` *sets* `x` to zero, rather than checking whether it is zero. – dfeuer Apr 05 '14 at 22:36
  • 1
    It's also worth noting that turning on compiler warnings might help detect these uses of assignment where comparison is intended. I don't know about VC++, but `gcc` certainly produces this warning. – Emmet Apr 05 '14 at 22:41
  • What makes you think 0 doesn't have a square root? It's only negative numbers that don't. – Ben Voigt Apr 05 '14 at 22:41
  • Well the problem was found, i made an error, it wasn't = but "<" which make a lot more sense. – user3502337 Apr 05 '14 at 22:51

1 Answers1

6

In this line:

  if (x = 0.0)

you're not comparing x with 0, but rather assigning the value 0 to x, which yields false in the "if" statementent, I presume you wanted to use the equality operator ==.

This is quite a common problem (confusing = with ==, and some languages (not c++) even have ===) so don't worry, it seems that you made an effort to find the cause and the question has everything needed to answer it, good job and have fun learning.

lccarrasco
  • 2,031
  • 1
  • 17
  • 20