VC ++中的sqrt()始终具有0值

时间:2014-04-05 22:34:19

标签: c++ visual-c++ sqrt math.sqrt

我对fonction sqrt()有一些问题!我是一个相当初学者,所以请放纵,答案可能非常简单。所以这是我的代码:

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

我的问题是,当我输入一个号码(它被存储,我在cout之前用cout检查过它&#34;以防它是它&#34;)是当sqrt(x);它只告诉程序,无论我输入什么,x和racx都是0。我真的不知道它会是什么。我还试图改变#include for#34; math.h&#34;并且仍然是一样的,所以我认为我的代码在某处是错误的。

如果你想知道在Windows 7最终的64位中使用Visual c ++ 2013。

PS:你可以注意到我的第一语言是法语,但不要担心我非常了解英语,即使我写作不好:P。

无论如何,谢谢你的关注和帮助!我们将不胜感激!

1 个答案:

答案 0 :(得分:4)

在这一行:

  if (x = 0.0)

你不是将x与0进行比较,而是将值0分配给x,这会在“if”状态命令中产生 false ,我认为你想要使用等于运算符==。

这是一个非常普遍的问题(混淆= = =,有些语言(不是c ++)甚至有===)所以不要担心,似乎你努力找到原因而问题已经存在一切都需要回答,做得好,学习有趣。