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

Always have 0 value from sqrt() in VC++

本文关键字:中的 sqrt VC++      更新时间:2023-10-16

我对 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检查了它,然后在这里发布它"以防万一")是sqrt(x);它只告诉程序x和racx是0,无论我键入什么。我真的不知道它会是什么。我还尝试更改"math.h"的 #include,并且仍然是相同的,所以我认为我的代码在某处是错误的。

我使用 Visual c ++ 2013 如果你想知道在 Windows 7 终极 64 位。

PS:正如你所注意到的,我的第一语言是法语,但不要担心,即使我不擅长写:P,我也非常了解英语。

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

在这一行中:

  if (x = 0.0)

您不是将 x 与 0 进行比较,而是将值 0 分配给 x,这在"if"语句中产生 false,我假设您想使用相等运算符 ==。

这是一个相当普遍的问题(混淆=与==,有些语言(不是c ++)甚至有===),所以不用担心,看来你努力寻找原因,问题有回答它所需的一切,干得好,学习愉快。