如何从用户输入中打印多个浮点数,并且只有其中一些浮点数带有特定的小数位数



我正在尝试打印多个浮点值,但其中只有一些需要是特定的小数位数。用户将输入两个浮点值,一个宽度和一个高度。然后程序将使用这两个值计算周长和面积。然后,它将打印插入方程中的值,并只显示小数点后一位的答案。

因此,一个例子如下:

Width: 3.14
Height: 4.2
Area: 3.14 * 4.2 = 13.2
Perimeter: 2 * (3.14 + 4.2) = 14.7

我遇到的问题是,当我打印输出时,我无法让它打印用户输入的浮点值的确切值,也无法让它只打印出小数点后一位的答案。我试过使用setprecision和printf,但就是无法使用它。我试着回答了以下关于显示精确小数位数的问题,但没有什么能满足我需要做的

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float width = 0;
float height = 0;
cout << "Rectangle Calculator" << endl;
cout << "Please enter the width: ";
cin >> width;
cout << "Please enter the height: ";
cin >> height;
float area = width * height;
float perimeter = 2 * (width + height);
cout << "Area: " << width << " * " << height << " = " << fixed << setprecision(1) << area << endl;
cout << "Perimeter: 2 * (" << width << " + " << height << ")" << " = " << fixed << setprecision(1) << perimeter;
return 0;
}

如果我理解正确,您希望以用户用于输入的精度打印出来。您可以通过首先将输入保存在std::string中并从中计算精度来实现这一点。使用2个输入的最大精度。

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
bool is_valid_float(std::string str) {
std::istringstream iss(str);
float test;
iss >> std::noskipws >> test;
return iss.eof() && !iss.fail();
}

unsigned get_precision(std::string input) {
for (unsigned i = 0u; i < input.length(); ++i) {
if (input[i] == '.') {
return (input.length() - i - 1);
}
}
return 0u;
}
int main() {
float width = 0;
float height = 0;
std::cout << "Rectangle Calculatornn";

std::string input;
do {
std::cout << "Please enter the width: ";
std::cin >> input;
if (!is_valid_float(input)) {
std::cout << "invalid inputn";
}
else {
break;
}
} while (true);
unsigned max_precision = get_precision(input);
width = std::atof(input.c_str());
do {
std::cout << "Please enter the height: ";
std::cin >> input;
if (!is_valid_float(input)) {
std::cout << "invalid inputn";
}
else {
break;
}
} while (true);
max_precision = std::max(max_precision, get_precision(input));
height = std::atof(input.c_str());
float area = width * height;
float perimeter = 2 * (width + height);
std::cout << "nArea: " << width << " * " << height << " = " << std::fixed << std::setprecision(max_precision) << area << 'n';
std::cout << "Perimeter: 2 * (" << width << " + " << height << ")" << " = " << std::fixed << std::setprecision(max_precision) << perimeter << 'n';
}

示例运行:

Rectangle Calculator
Please enter the width: 3.4
Please enter the height: 1.5
Area: 3.4 * 1.5 = 5.1
Perimeter: 2 * (3.4 + 1.5) = 9.8
Rectangle Calculator
Please enter the width: 15.125
Please enter the height: 22.0875
Area: 15.125 * 22.0875 = 334.0734
Perimeter: 2 * (15.1250 + 22.0875) = 74.4250

注意,float只有大约7.225个正确的小数位数:

Rectangle Calculator
Please enter the width: 2.1111111111111
Please enter the height: 3.9999999999999
Area: 2.11111 * 4 = 8.4444446563721
Perimeter: 2 * (2.1111111640930 + 4.0000000000000) = 12.2222223281860

因此您应该在程序中使用double而不是float。它实现了CCD_ 6正确的小数位数。

最新更新