gpt4 book ai didi

c++ - 如何解决除以零 C++

转载 作者:太空狗 更新时间:2023-10-29 20:55:45 24 4
gpt4 key购买 nike

我对编程很陌生,因为我必须上一门课才开始。

在实验室中,我们必须编写一个简单的计算器(加法、减法、除法和乘法),然后插入老师给我们的集合数字。当然,其中两组数字中有零。您如何将其编码为未定义而不是浮点异常(核心已转储)

#include <iostream>
#include <cmath>

using namespace std;

int main() {

int a;
int b;
float c;
float d;
float e;
float f;
float g;
float h;
float i;
float j;

cout << "Enter value for a\n";
cout << "Enter value for b\n";
cout << "Then press return.\n";

cin >> a;
cin >> b;

c = a + b;
d = a - b;
e = a * b;
f = a / b;

g = sqrt (c);
h = sqrt (d);
i = sqrt (e);
j = sqrt (f);

cout << a << " value for a\n";
cout << b << " value for b\n";
cout << "value for c is " << c << " \n";
cout << "value for d is " << d << " \n";
cout << "value for e is " << e << " \n";
cout << "value for f is " << f << " \n";
cout << "value for g is " << g << " \n";
cout << "value for h is " << h << " \n";
cout << "value for i is " << i << " \n";
cout << "value for j is " << j << " \n";

return 0;
}

最佳答案

也许更好的方法是清理您的输入。 “如果用户为 b 输入 0,则说未定义,否则,尝试计算。”

你还会遇到这个问题,如果 a 小于 bsqrt() 函数将抛出也是一个错误(并非设计用于处理负输入)。

关于c++ - 如何解决除以零 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050502/

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