2023-12-16 课后练习(复习+结构体练习)

题目:分式运算,1-1/2+1/3-1/4+…+1/99-1/100

代码:

#include
int main()
{
	int i = 1;//项数,初始值为1
	double deno = 2;//分母,初始值为2,从第二项开始
	double n = 1;//项的数值,初始值为1
	double sum=1;//和的初始值为1
	while (deno <= 100)
	{
		i++;
		if (i % 2 == 0)//如果为偶数项则改变正负号
		{
			deno = -deno;
		}
		n = 1 / deno;
		sum += n;
		deno++;
	}
	printf("%.9lf", sum);
	return 0;
}

另一种方法:

#include
int main()
{
	int i = 1;//项数,初始值为1
	double deno = 2;//分母,初始值为2,从第二项开始
	double n = 1;//项的数值,初始值为1
	double sum = 1;//和的初始值为1
	while (deno <= 100)
	{
		i++;
		n = 1 / deno;
		if (i % 2 == 0)//如果为偶数项则改变正负号
		{
			n = -n;
		}
		sum += n;
		deno++;
	}
	printf("%.9lf", sum);
	return 0;
}

运行结果:

0.688172179

题目:投票结果

代码:

#include
struct Student
{
	char name[20];//候选人姓名
	int count;//候选人得票数
}
leader[3]={"Messi",0,"Mbappe",0,"Haaland",0};//定义结构体数组初始化

int main()
{
	int i, j;
	char leader_name[20];
	for (i = 1; i <= 4; i++)
	{
		scanf("%s", leader_name);
		for (j = 0; j < 3; j++)
		{
			if (strcmp(leader_name, leader[j].name) == 0)
				leader[j].count++;
		}
	}
	printf("\nResult:\n");
	for (i = 0; i < 3; i++)
	{
		printf("%5s:%d\n", leader[i].name, leader[i].count);
	}
	return 0;
}

运行结果:

Messi
Mbappe
Haaland
Messi

Result:
Messi:2
Mbappe:1
Haaland:1

 题目:指向结构体变量的指针

代码:

#include
#include
struct date
{
	int year, month, day;
};

struct student
{
	int num;
	char name[20];
	char sex;
	struct date bday;
	double score;
};
int main()
{
	struct student s;
	struct student* p = &s;
	s.num = 10;
	strcpy(s.name, "Messi");
	s.score = 99.9;
	printf("%d,%s,%lf\n", p->num, p->name, p->score);
	return 0;
}

运行结果:

10,Messi,99.900000

你可能感兴趣的:(算法,c++,数据结构,c语言)