[英]Circle Area C++ Truncation Calculation Problem
我嘗試在 C++ 中創建一個控制台應用程序,該應用程序使用以下等式計算圓的面積:pi 乘以半徑的平方。 順便說一下,我使用 Visual Studio 制作控制台應用程序。 這些是程序執行的步驟:
這是我的代碼:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main() {
//The formula for calculating the area of a circle is Pi times radius squared
double input = NULL;
const double pi = 3.14;
cout << "Circle Area Calculator" << endl;
cout << "To use this calculator, enter in the radius and we will process it." << endl;
cout << "If you want to calculate the area yourself, good choice! Use the formula: 3.14 * radius squared(means multiply radius by itself)" << endl;
cout << "NOTE: If you radius value has a decimal, ignore this. If it doesn't, add .0 to the end of the radius value. It will not say the measurement, so make sure you put the measurement(example: cm, in) at the end" << endl;
cout << "Enter in your radius: " << input << endl;
cin >> input;
double acc = pi * input * input;
cout << "The area: " << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
// When generating the answer, the thing can sometimes round the number(which is bad)
}
我曾經有一個 int 作為輸入變量,但我將其更改為 double(float) 變量。 因為它是雙精度(大浮點數),所以我認為它可以解決截斷問題。 仍然有時會出現截斷(舍入)問題。
您可以使用 std::setprecision() 強制顯示一組數字,例如:
#include <iomanip>
// ...
double acc = pi * input * input;
int precision = log10(acc) + 7; // 7 = number of decimals + 1
cout << "The area: " << setprecision(precision) << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
將產生 6 個十進制數字。
例如:輸入:211.123456 將打印出來
The area: 139959.576934. Don't forget to add the measurement type! (example: cm, in)
請注意,雙精度的最大精度總共為 19 位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.