gpt4 book ai didi

c++ - 如何计算每次读入一个字符的个数?

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:09 25 4
gpt4 key购买 nike

我是 C++ 类的学生。我需要帮助完成一项任务。

"Read from a text file called salaries.txt that contains the following format:

M321232.34
F43234.34
M23432.23
M191929.34

字母“M”和“F”代表性别,数字代表他们的薪水。每次读一个时数一数男性的数量,并且将每个男性工资加到累计的 totalMaleSalary 中。做同样的女性。在循环结束时计算女性平均工资和平均男性工资 - 显示您的结果并确定两个平均值中哪个更大。”

我如何计算男性人数并添加每个人的薪水?

这是我的:

int main(){

int male=0, female=0;
double salary,totalMaleSalary=0,totalFemaleSalary=0;
char gender;

ifstream fin;
fin.open("salary.txt");
do{
fin>>gender>>salary;
if(gender=='M'){
male=male+1;
totalMaleSalary=salary+totalMaleSalary;
}
if(gender=='F'){
female=female+1;
totalFemaleSalary=salary+totalFemaleSalary;
}

cout<<"Number of Males is "<<male<<endl;
cout<<"Number of Females is "<<female<<endl;
cout<<"Total Male Salary is "<<totalMaleSalary<<endl;
cout<<"Total Female Salary is "<<totalFemaleSalary<<endl;
cout<<"Average Male salary is "<<totalMaleSalary/male<<endl;
cout<<"Average Female salary is "<<totalMaleSalary/female<<endl;

}while(!fin.eof());


fin.close();
return 0;
}

最佳答案

  1. 不要假定文件已成功打开。使用 if ( !is )... .
  2. 不要使用 eof() .提取成功时读取:while ( is >>... .
  3. 读取整个文件后必须显示结果:cout <<...必须在外循环。

你的固定程序:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
std::ifstream is( "salary.txt" );
if ( !is )
return -1; // failed to open

int male = 0, female = 0;
double salary, totalMaleSalary = 0, totalFemaleSalary = 0;
char gender;

while ( is >> gender >> salary )
{
if ( gender == 'M' )
{
male = male + 1;
totalMaleSalary = salary + totalMaleSalary;
}
else if ( gender == 'F' )
{
female = female + 1;
totalFemaleSalary = salary + totalFemaleSalary;
}
else
return -2; // unknown
};

cout << "Number of Males is " << male << endl;
cout << "Number of Females is " << female << endl;
cout << "Total Male Salary is " << totalMaleSalary << endl;
cout << "Total Female Salary is " << totalFemaleSalary << endl;
cout << "Average Male salary is " << totalMaleSalary / male << endl;
cout << "Average Female salary is " << totalMaleSalary / female << endl;

return 0;
}

关于c++ - 如何计算每次读入一个字符的个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47467570/

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