using namespace std;
/*
功能:
输入:double dval 输入double浮点数
int nlen 取小数位数
bool bval 是否要四舍五入
输出:
返回:char* :字符串(有nlen位小数)
*/
char* doubleConvert(double dval,int nlen ,bool bval)
{
char buf[100];
sprintf_s(buf,100,"%lf",dval);
int buf_len = strlen(buf);
int point_pos = char_traits::find(buf, buf_len,'.')-buf;
int total_len = point_pos+nlen;
if ( buf_len > total_len && bval && buf[total_len+1]>='5') buf[total_len]+=1;
buf[total_len+1] = '\0';
return buf;
}
/*
功能:计算所有选 手的平均得分。
输入参数(指针指向的内存区域保证有效):
char* pInputString:字符串数组,是输入的成绩和姓名。分数是0-10的整数,名字的长度不超过30个字符
int Num:整数,参赛选手的数量,2 <= Num <= 26。
输出参数(指针指向的内存区域保证有效):
char* pResult:一块buffer,输出所有参赛者的姓名和平均分(保留2位小数)。格式要求如下:
1、姓名在前,平均分在后,中间由一个空格隔开;
2、每行参赛者的成绩占一行(最后一个参赛者成绩之后不要换行符);
3、输出成绩按输入顺序排序。
返回值:
void
*/
void GetResult(char* pInput[], int Num, char *pResult)
{
if(pInput == NULL || Num < 1 || Num >26)
return;
char myResult[10000] = "";
for (int i = 0; i < Num; i++)
{
char* temp = pInput[i];
char* nameTemp = "";//名字
int scores[7] = {0};//7个分数
int scoreIndex = 0;
//获取名字和分数
while (*temp != '\0')
{
if (*temp == ' ')
{
scoreIndex++;
}else if (*temp > 47 && *temp < 58)
{
scores[scoreIndex] = scores[scoreIndex] * 10 + *temp -48;
}else
{
if(strlen(temp) < 1 || strlen(temp) > 30 || scoreIndex != 7)
return;
nameTemp = temp;
break;
}
temp++;
}
//计算平均分
double scoreAvg = scores[0];//平均分
int scoreMax = scores[0];//最大值
int scoreMin = scores[0];//最小值
for (int j = 1; j < 7; j++)
{
if (scoreMax < scores[j])
scoreMax = scores[j];
if (scoreMin > scores[j])
scoreMin = scores[j];
scoreAvg += scores[j];
}
scoreAvg = (scoreAvg - scoreMax - scoreMin) / 5;
char* strAvg = doubleConvert(scoreAvg, 2, true);
char tempResult[100] = "";
strcpy_s(tempResult, 31, nameTemp);
strcat_s(tempResult, strlen(tempResult) + 2, " ");
strcat_s(tempResult, strlen(tempResult) + strlen(strAvg) + 1, strAvg);
strcat_s(myResult, strlen(myResult) + strlen(tempResult) + 1, tempResult);
if(i != Num - 1)
strcat_s(myResult, strlen(myResult) + 2, "\n");
}
strcpy_s(pResult, strlen(myResult) + 1, myResult);
return;
}