首页 > 解决方案 > 不在 C++ 中将数组的第一个元素打印到十进制精度

问题描述

在为数量> 1000 提供 10% 的折扣并使用数组实现此目标后,我将输入“成本”和“数量”并将总计打印为“成本*数量”。

但是,当我尝试打印输出时,输出的第一行并没有给出精确的十进制值。

问题陈述:https ://www.codechef.com/problems/FLOW009/

#include <iostream>
#include <stdlib.h>

int main(){

    int n;
    int comp = 0;
    std::cout.precision(6);

    std::cin >> n;

    float cost[n];
    float qty[n];
    float total[n];

    for (int i=0; i<n; i++){
        std::cin>>cost[i]>>qty[i];
    }

    while (comp < n){
        if(cost[comp]>1000){
            cost[comp] = cost[comp] - cost[comp]*0.10;
        }
        comp++;
    }

    for(int z=0; z<n; z++){
        total[z] = cost[z]*qty[z];
    }

    for (int j=0; j<n; j++){
        std::cout<< total[j] << std::fixed << std::endl;
    }

}

我已经使用std::cout.precision()并且std::fixed正确

输入:

3 
100 120
10 20
1200 20

预期输出:

12000.000000
200.000000
21600.000000

实际输出:

12000
200.000000
21600.000000

标签: c++

解决方案


问题是您在发送到之前输出第一个值(在第一次运行输出循环时)!试试这个简单的修正:std::fixedstd::cout

for (int j = 0; j < n; j++) {
//  std::cout<< total[j] << std::fixed << std::endl; // total[0] goes out BEFORE std::fixed!
    std::cout << std::fixed << total[j] << std::endl; // Send std::fixed BEFORE the number!
}

或者,为了更有效的方式,只需std::fixed在循环之前发送一次:

std::cout << std::fixed;
for (int j = 0; j < n; j++) {
    std::cout << total[j] << std::endl;
}

推荐阅读