c++ - 不在 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
解决方案
问题是您在发送到之前输出第一个值(在第一次运行输出循环时)!试试这个简单的修正:std::fixed
std::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;
}
推荐阅读
- c++ - 将 boost::json 静态库与 cmake 一起使用
- android - getLastLocation() 仅在三到四次尝试后返回位置
- laravel - 谁能帮我从每个模型做 laravel 通知过程。例如:我有两个模型,一个是护照,另一个是 voterid。?
- c# - 如果可以在特定类型上调用扩展方法,则通过反射检查的稳健方法
- aws-lambda - 如何在本地调试和运行多个 lambda
- r - 在 R 中:按组具有值 0、1 和 2 的子集观测值
- javascript - d3 v6 汇总中的动态键数
- react-native - 在 React Native 项目中更改 android SDK
- typescript - 如何用正确的类型替换函数参数?
- x11 - SDL2,X11,无桌面环境:没有焦点的应用程序,没有输入事件