gpt4 book ai didi

c++ - 设置精度和文件

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:49 27 4
gpt4 key购买 nike

我有两个问题:
1. 如何让某个文件没有输入就不会继续?
2. 我的数字不显示小数点,我不明白为什么,我使用了 setprecision

    #include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
string file;
int Bailey ,
Harrison,
Grant,
Peterson,
Hsu,
Bowles,
Anderson,
Nguyen,
Sharp,
Jones,
McMillan,
Gabriel;
int m, f , cc, un;


cout << " Welcome to Maggie's Student Survey!"; //Introduction
cout << endl;
cout << " Enter the file name you wish to open: " <<endl;// promts the user to enter the file name they want to open
getline(cin, file);
inFile.open(file);
outFile.open(file);
cout << " The Student's Genders, Colleges, and Scores:" << endl;
cout << "\n Bailey M CC 68"
"\n Harrison F CC 71"
"\n Grant M UN 75"
"\n Peterson F UN 69"
"\n Hsu M UN 79"
"\n Bowles M CC 75"
"\n Anderson F UN 64"
"\n Nguyen F CC 68"
"\n Sharp F CC 75"
"\n Jones M UN 75"
"\n McMillan F UN 80"
"\n Gabriel F UN 62 " << endl; //the data file so the user can see what they opened
m = (75 + 79 + 75 + 75) / 4; // average will be 76
f = (71 + 69 + 64 + 68 + 75 + 80 + 62) / 7; //average will be 69.85
cc = (71 + 75 + 68 + 75) / 4; //average will be 72.25
un = (75 + 69 + 79 + 64 + 75 + 80 + 62) / 7; // average will be 72
cout << " Total Males Average Scores: " << std::setprecision(2) << m << endl;
cout << " Total Females Average Scores: " << std::setprecision(2) << f << endl;
cout << " Total Community College Average Scores " << std::setprecision(2) << cc << endl;
cout << " Total University Average Scores: " << std::setprecision(2) << un << endl;

system("pause");

最佳答案

关于你的第二个问题,我想出了一个解决方案,首先你需要将 m、f、cc、un 声明为 double ,而不是整数。然后尝试将其他数字存储为其他变量。例如抄送:

 #include <iostream>
#include <iomanip>


int main()
{
double a, b, c, d; // or ints, here it doesn't matter
a = 71;
b = 75;
c = 68;
d = 75;
double cc = (a + b + c + d) / 4; //average will be 72.25
std::cout << " Total Community College Average Scores " << std::setprecision(4) << cc << '\n';
system("pause");
}

如果你这样做,精度就可以了。我设置为4是为了显示你的号码,2个不够。

其他解决方案(可能更简单):

 #include <iostream>
#include <iomanip>


int main()
{
double p;
p = 71 + 75 + 68 + 75;
double cc = p / 4; //average will be 72.25
std::cout << " Total Community College Average Scores " << std::setprecision(4) << cc << '\n';
system("pause");
}

关于c++ - 设置精度和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932309/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com