如果只使用'iostream'和'string'库,可以使用'std::stringstream'类来实现保留3位小数和上下行小数点对齐的功能。以下是一个示例代码:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// 将浮点数转换为字符串,保留指定位数的小数
string formatNumber(double number, int decimalPlaces) {
    stringstream ss;
    ss.precision(decimalPlaces);
    ss << fixed << number;
    return ss.str();
}

int main() {
    const int MAX_VALUES = 5;  // 可修改为需要输入的数值数量
    double values[MAX_VALUES];

    // 输入数值
    cout << "请输入 " << MAX_VALUES << " 个数值:" << endl;
    for (int i = 0; i < MAX_VALUES; i++) {
        cin >> values[i];
    }

    // 找到最大的小数位数
    int maxDecimalPlaces = 0;
    for (int i = 0; i < MAX_VALUES; i++) {
        double integerPart;
        double decimalPart = modf(values[i], &integerPart);
        int decimalPlaces = 0;
        while (decimalPart > 0.001) {
            decimalPart *= 10;
            decimalPart = modf(decimalPart, &integerPart);
            decimalPlaces++;
        }
        if (decimalPlaces > maxDecimalPlaces) {
            maxDecimalPlaces = decimalPlaces;
        }
    }

    // 输出数值并进行上下行小数点对齐
    cout << "输出结果:" << endl;
    for (int i = 0; i < MAX_VALUES; i++) {
        // 将数值转换为字符串,并保留3位小数
        string formattedNumber = formatNumber(values[i], 3);

        // 计算当前数值的小数位数
        double integerPart;
        double decimalPart = modf(values[i], &integerPart);
        int decimalPlaces = 0;
        while (decimalPart > 0.001) {
            decimalPart *= 10;
            decimalPart = modf(decimalPart, &integerPart);
            decimalPlaces++;
        }

        // 根据最大小数位数进行对齐
        string padding(maxDecimalPlaces - decimalPlaces, ' ');
        cout << padding << formattedNumber << endl;
    }

    return 0;
}

在这个示例代码中,我们使用'std::stringstream'来将浮点数转换为字符串,并保留指定位数的小数。通过自定义格式化函数,我们可以实现保留3位小数的效果。然后,我们使用字符串填充来实现上下行小数点对齐的效果。

C++ iostream 和 string 库实现保留三位小数并对齐输出

原文地址: https://www.cveoy.top/t/topic/kmG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录