什么是高精度?高精度又怎么用?这种问题进场存在于我这个蒟蒻的心里,直到学了高精度。
高精度的原理是通过字符串来实现比longlong还大的数据的运算。基本就是按照我们手动运算的逻辑来写,话不多说,题目奉上:
问题描述
计算A/B的精确值,设 A,B 是以一般整数输入,计算结果精确到小数后 20位
输入数据 1
4 3
输出数据 1
4/3=1.33333333333333333333
输入数据 2
6 5
输出数据 2
6/5=1.2
输入数据 3
60 5
输出数据 3
60/5=12.0
话不多说,代码奉上:
#include <iostream>
#include <string>
using namespace std;
string divide(int A, int B) {
string result;
int quotient = A / B;
int remainder = A % B;
result += to_string(quotient) + '.';
int decimal_places = 0;
while (decimal_places < 20) {
remainder *= 10;
quotient = remainder / B;
result += to_string(quotient);
remainder = remainder % B;
decimal_places += 1;
}
return result;
}
int main() {
int A, B;
cin >> A >> B; \
string result = divide(A, B);
cout << A << '/' << B << '=' << result << endl; \
return 0;
}
是不是有那么亿点点简单,难题就是要多练。