C++二次码错误
C++ Quadratic Code Errors
我在下面的代码中遇到了问题:
#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
int main()
{
ifstream fin("input.txt");
ofstream fout("output.txt");
float discriminant, A, B, C, root1, root2;
fin >> A >> B >> C;
while (A != -99)
{
discriminant = (pow(B, 2.0) - 4 * A*C);
if (A == 0)
{
fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
}
else if (discriminant > 0)
{
root1 = (-B - sqrt(discriminant)) / (2.0*A);
root2 = (-B + sqrt(discriminant)) / (2.0*A);
fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
}
else if (discriminant == 0)
{
fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
}
else
{
fout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
}
fin >> A >> B >> C;
}
fout.close();
ifstream fin2("output.txt");
fin2 >> A >> B >> C >> root1 >> root2;
while (!fin2.eof())
{
cout << A << "t" << B << "t" << C << "t" << root1 << "t" << root2 << endl;
fin2 >> A >> B >> C >> root1 >> root2;
}
cout << endl;
cout << "Coded by Paye W. Kialain" << "t"<< endl;
system("pause");
return 0;
}
在项目描述中,我被告知创建一个包含 a、b 和 c 的输入文件,我做到了。输出的格式也正确。它是一个显示 a、b 和 c 值以及 2 个计算根的表格。然而,根的计算似乎不对。我的 if 语句是问题吗?
语句 discriminant == 0
和 A == 0
是危险的比较,因为discriminant
和A
是float
s。 浮点计算通常伴随着浮点误差(想想你在数学近似中得到的错误)。
考虑这个浮点错误的简单示例:
#include <iostream>
#include <string>
int main()
{
float a = 3.0;
float b = 10.0;
std::cout.precision(20);
std::cout << a/b << std::endl;
}
3.0/10.0,这是初级数学!您希望结果为 0.3。但是,事实证明,结果是 0.30000001192092895508。如果a
和b
double
,则结果将为 0.2999999999999999889。这是因为浮点数以二进制表示的方式不允许准确表示 0.3。现在想象一下,如果我有像if(a/b == 0.3)
这样的代码会发生什么。条件永远不会得到满足。
此问题的解决方案是引入 epsilon 值。此 epsilon 值基本上用作容错值。
float a = 3.0;
float b = 10.0;
const float epsilon = 0.000001;
if(fabs(a/b - 0.3) < epsilon) {
std::cout << "a/b is equal to 0.3!" << std::endl;
}
相关文章:
- 输出 0 和 -0 的二次公式,与给定的项无关
- 处理所有二次公式结果
- 两个嵌套循环的运行时间复杂性:二次型还是线性
- Cgal二次规划目标函数
- 二次代数建议数组等返回功能
- 无法从数组二次表达式中检索数据值
- 创建二次公式求解器-范围中未声明的变量
- C++:你如何确定一个解是微不足道的还是不存在的二次函数?
- 如何将二次贝塞尔曲线代码转换为三次贝塞尔曲线
- 为什么使用STL排序()进行二次时间排序
- inotify 多次错误地通知新文件
- omp并行用于二次筛的无优化
- 分段故障:SET C++11中的二次排序
- C++识别以像素为单位的二次和三次显示
- 在 Vulkan 中加载非二次幂纹理
- C++二次码错误
- sqrt() 使用 <math.h) 在二次公式中的意外结果>
- 如何顺时针交换二次矩阵的四分之一(从左上角开始)
- 只实例化派生类一次错误的 OOP
- 编写二次公式程序时出现编译错误