如何在公式中使用整数,结果是精确的两位小数



所以我的目标是编写求解二次方程的程序。但是a、h和k对应的值必须是整数,而x的值必须为两位小数的双精度实数。

我的问题出现了,当我在公式中运行int时,它只会返回整数。我知道,如果我把int从int改为double,程序就会正确运行,但我的教授希望它们是整数。

#include <iostream>             
#include <cmath>
#include <typeinfo>
#include <iomanip>
#include <string>
using namespace std;
int  main( )
{
int a = 3,h = 4,k = 5 ;
double x1;
x1 = -h + sqrt(k/a);
x1 = round(x1*100.00)/100.00;
cout << "The solutions for the equation are: " << endl << "                            " << "x1: " <<setprecision(2) << fixed << x1;
}

您可以使用static_cast<double>:

#include <iostream>
#include <cmath>
#include <typeinfo>
#include <iomanip>
#include <string>
using namespace std;
int main() {
string name;
int a, h, k;
double x1, x2;
cout << "Please enter your name: ";
cin >> name;
cout << endl << "Please enter the known terms for the quadratic equation" << endl;
cout << "a: ";
cin >> a;
cout << endl << "h: ";
cin >> h;
cout << endl << "k: "; 
cin >> k;
cout << endl << "Thanks, " << name << "";
// Calculates x1 using the formula -h + square root(k/a)
x1 = -h + sqrt(static_cast<double>(k)/a);
// Rounds x1 to the second decimal digit and reassigns it to x1
x1 = round(x1*100.00)/100.00;
// Ditto for x2
x2 = -h - sqrt(static_cast<double>(k)/a);
x2 = round(x2*100.00)/100;
cout << "The solutions for the equation are: " << endl << "                            " << "x1: " << setprecision(2) << fixed << x1;
cout << endl << "                            " << "x2: " << setprecision(2) << fixed << x2;
} 

因为这两个操作数都是整数,所以它使用整数除法,然后四舍五入。通过将一个操作数强制转换为double,我们使用正则除法。

其他评论:我修正了x2的公式,它使用了+而不是-。此外,我还做了一些缩进和其他格式设置。这是一个荒谬的过度评论的案例;我知道大多数台词的作用,它们并没有那么复杂。我删除了大部分不必要的评论。

最新更新