gpt4 book ai didi

c++ - 为什么我将nan作为以下代码的输出?

转载 作者:行者123 更新时间:2023-12-02 10:15:39 25 4
gpt4 key购买 nike

我正在尝试制作一个用于查找方程式根源的计算器。我使用字符串获取数字,然后将带有stringstream的字符串转换为它们的数字类型以进行计算;

因为我想做一个循环,以便用户可以随意使用计算器,直到他们退出输入abc值的任何部分。

当我写a=1b=2c=1时,我得到x1x2的nan。

我分别检查了isnan(d)isnan(-b/2*a),但它们不是nan。而且它们也不是0/0。为什么我越来越难,这与我使用弦乐的方式有关吗?

    #include<iostream>
#include<sstream>
#include<string>
#include<cmath>

using namespace std;

void root_calculator(string stra="", string strb="", string strc="")
{
int a=0,b=0,c=0;
float d=0.0,x1=0.0,x2=0.0,real=0.0,im=0.0;

d = (b*b) - (4*a*c);

if (d >= 0)
{
x1= (-b + (sqrt(d)))/(2*a);
x2= (-b - (sqrt(d)))/(2*a);
cout << "x1= "<< x1 << " x2= " << x2 << endl;
}
else{
cout << "Roots are imaginary";
real = -b / (2*a);
im = (sqrt (-d)) / (2*a);
cout << "x1= " << real << "+" << im << endl;
cout << "x1= " << real << "-" << im << endl;
}

}

int main()
{
int a=0,b=0,c=0;
string stra,strb,strc;

cout << "enter a,b,c \n>>a=";
getline(cin,stra);
stringstream(stra) >> a;
cout << "\n>>b=";
getline(cin,strb);
stringstream(strb) >> b;
cout << "\n>>c=";
getline(cin,strc);
stringstream(strc) >> c;

while (stra!= "quit" && strb!= "quit" && strc!="quit")
{
root_calculator(stra,strb,strc);

cout << ">>a=";
getline(cin,stra);
stringstream(stra)>>a;
cout << "\n>>b=";
getline(cin,strb);
stringstream(strb)>>b;
cout << "\n>>c=";
getline(cin,strc);
stringstream(strc)>>c;
}

return 0;
}

最佳答案

您的代码在这里失败:

x1= (-b + (sqrt(d)))/(2*a);
x2= (-b - (sqrt(d)))/(2*a);

因为这:
void root_calculator(string stra="", string strb="", string strc="")
{
int a=0,b=0,c=0;

尤其是因为从未使用过参数stra,strb和strc ...
所以你最终被零除...

关于c++ - 为什么我将nan作为以下代码的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62022178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com