犯二的菜鸟

本文通过一个C++小程序示例,展示了在文件读取过程中常见的编程错误,并介绍了如何从文件中读取数据到数组,以及根据特定规则计算最终分数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

coding这种事情,一个小疏忽,或者实践不够,就会犯很多错误。现将今天写的一个小程序的错误指出,以便以后查看。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//预定义
#define MAX_LENGTH 100

//函数声明
int cal_score(int score[], int judge_type[], int n);

int _tmain(int argc, _TCHAR* argv[])
{  
	string filename;
	int score[MAX_LENGTH];
	int judge_type[MAX_LENGTH];
	int temp=0;

	cout<<"Get score from file: "<<ends;
        cin>>filename;
	ifstream input(filename);
	if(!input){
		cerr<<"read file fail."<<endl;
		return 0;
	}else{
		/*此处注意 不能写为input >> score[temp++], ++操作符优先于 >>。另外这里输入时,可以直接存入int.无须再做转换。*/
		while(input >> (score[temp])) temp++;
	}
	input.close();
	cout<<endl<<"Get scores successfully."<<endl;
    
	cout<<"Get judge type from file: "<<ends;
        cin>>filename;
	input.open(filename);
	if(!input){
		cerr<<"read file fail."<<endl;
		return 0;
	}else{
		temp=0;
		while(input >> (judge_type[temp])) temp++;
	}
	input.close();
	cout<<endl<<"Get judge type successfully."<<endl;

        //算分
	int finalscore = cal_score(score, judge_type,temp);
	cout<<"The score of current contestant is "<<finalscore<<endl;

	return 0;
}

//分数记录函数
int cal_score(int score[], int judge_type[], int n) {

        //创建两个scores总数变量,以及专家评委个数变量
	int sumSpecial=0;
	int sumNormal=0;
	int countSpecial=0;

	//一次遍历两个数据,更新总数值
	int j=0;
	for (j;j<n;j++){
		if(judge_type[j] == 1) {
			sumSpecial+=score[j];
			countSpecial++;
		}else sumNormal+=score[j];
	}

	//根据countSpecial是否== n来计算得分
	int finalScore=0;
	if(countSpecial == n )
		finalScore = sumSpecial/countSpecial;
	else
		finalScore = sumSpecial/countSpecial*0.6 + sumNormal/(n-countSpecial)*0.4;

	return finalScore;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值