一、最大子数组
//求某数组的最大子数组
//最优方法,时间复杂度O(n)
//和最大的子序列的第一个元素肯定是正数
//因为元素有正有负,因此子序列的最大和一定大于0
#include <stdio.h>
#include <stdlib.h>
int main()
{
int MaxSum(int);
int shuzu[6] = {-10,20,50,-60,80,-90};
int MaxSum(int *shuzu);
{
int i;
int MaxSum = 0;
int Sum = 0;
for(i=0;i<6;i++)
{
Sum += shuzu[i];
if(Sum > MaxSum)
MaxSum = Sum;
//如果累加和出现小于0的情况,
//则和最大的子序列肯定不可能包含前面的元素,
//这时将累加和置0,从下个元素重新开始累加
if(Sum <= 0)
Sum = 0;
}
printf(" %d\n",MaxSum);
}
system("pause");
}
二、黄金点游戏
#include "atlstr.h"
#include "stdlib.h"
#include "math.h"
typedef struct gameplayer //玩家结构体
{
int name, score, win, fail;
float number, b;
}PLAYER; //玩家的姓名、分数、编号、输赢
void STARTGAME(FILE *fp); //初始化游戏
void GAMERULE(); //游戏规则
void CALCULATE_SCORE(PLAYER *p, float average, int number, FILE *fp);//计算比赛得分
int main()
{
//system("color 1D");
int opt;
FILE *fp;
while (1)
{
fp = fopen("goldgame.txt", "w+");
printf("\n 黄金点游戏 \n");
printf(" 1. 规则\n");
printf(" 2. 开始\n");
printf(" 3. 退出\n");
scanf("%d", &opt);
switch (opt)
{
case 1: GAMERULE(); break;
case 2: STARTGAME(fp); break;
case 3: exit(0); break;
default: { printf(" 输入错误,重新输入\n"); break; }
}
}
return 0;
}
void STARTGAME(FILE *fp)
{
PLAYER *p;
int i, j, playernumber, gamenumber;
int flag = 1;
float sum, average;
p = (PLAYER *)malloc(10 * sizeof(PLAYER)); //动态分配结构体数组
printf("输入玩家人数:");
scanf("%d", &playernumber);
if (playernumber>10)
{
p = (PLAYER *)realloc(p, playernumber*sizeof(PLAYER));//空间时不足增加额外的空间
}
printf("输入比赛轮数:");
scanf("%d", &gamenumber);
//printf("\n");
for (j = 0; j<gamenumber; j++)
{
printf("\n第%d轮比赛:\n", j + 1);
for (i = 0, sum = 0; i<playernumber; i++)//sum为总数和
{
if (flag == 1)
{
p[i].name = i + 1;
p[i].score = 0;
} //初始化 初值为0
printf(" 玩家%d: ", p[i].name);
scanf("%f", &p[i].number);
sum += p[i].number;
}
average = sum / playernumber; //计算平均值
average = (float)(average*0.618); //计算黄金点的值
printf(" 黄金点G值为:%f\n", average);
CALCULATE_SCORE(p, average, playernumber, fp);
flag = 0;
}
}
void CALCULATE_SCORE(PLAYER *p, float average, int number, FILE *fp)
{
int i;
char cha;
float max = (float)fabs(p[0].number - average);
float min = (float)fabs(p[0].number - average);
for (i = 0; i<number; i++) //统计 最大值、最小值
{
p[i].b = (float)fabs(p[i].number - average);
if (max<p[i].b)
max = p[i].b;
if (min>p[i].b)
min = p[i].b;
}
for (i = 0; i<number; i++) //每个玩家的得分
{
if (p[i].b == max)
{
p[i].score -= 2;
}
if (p[i].b == min)
{
p[i].score += number;
}
}
printf("累计比赛的得分:\n");
for (i = 0; i < number; i++) //依次输出每个玩家的得分
{
printf(" 玩家%d: %d\n", p[i].name, p[i].score);
}
while (1)
{
printf("是否继续 Y or N : ");
scanf("%c", &cha);
if (cha == 'y' || cha == 'Y')
{ break; }
else if (cha == 'n' || cha == 'N')
{ exit(0); }
}
}
void GAMERULE()//游戏规则
{
printf("N个同学(N>10),每人写一个0到100之间的有理数(不包括0或100),计算出平均值,再乘以0.618(所谓黄金分割常数),得到G。给出的数字最靠近G的同学得到N分,离G最远的同学得到-2分,其他同学得0分。\n");
}
标签:fp,int,average,float,number,软件工程,实验,printf From: https://www.cnblogs.com/xjlnl/p/16772859.html