以下是使用C++实现从键盘输入一批数值,并在输出时保留3位小数并进行上下行小数点对齐的示例代码:

#include <iostream>
#include <iomanip>
using namespace std;

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];
    }

    // 设置输出格式,保留3位小数
    cout << fixed << setprecision(3);

    // 找到最大的小数位数
    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++) {
        // 计算当前数值的小数位数
        double integerPart;
        double decimalPart = modf(values[i], &integerPart);
        int decimalPlaces = 0;
        while (decimalPart > 0.001) {
            decimalPart *= 10;
            decimalPart = modf(decimalPart, &integerPart);
            decimalPlaces++;
        }

        // 输出数值,并根据最大小数位数进行对齐
        cout << setw(maxDecimalPlaces + 4) << values[i] << endl;
    }

    return 0;
}

这段代码使用了setprecision函数来设置输出精度为3位小数。通过计算输入数值中的最大小数位数,确定了输出时需要的对齐宽度,并使用setw函数设置输出宽度。

C++实现保留三位小数并对齐输出数值

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

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