本文主要是介绍2023-12-16 课后练习(复习+结构体练习),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:分式运算,1-1/2+1/3-1/4+…+1/99-1/100
代码:
#include<stdio.h>
int main()
{int i = 1;//项数,初始值为1double deno = 2;//分母,初始值为2,从第二项开始double n = 1;//项的数值,初始值为1double sum=1;//和的初始值为1while (deno <= 100){i++;if (i % 2 == 0)//如果为偶数项则改变正负号{deno = -deno;}n = 1 / deno;sum += n;deno++;}printf("%.9lf", sum);return 0;
}
另一种方法:
#include<stdio.h>
int main()
{int i = 1;//项数,初始值为1double deno = 2;//分母,初始值为2,从第二项开始double n = 1;//项的数值,初始值为1double sum = 1;//和的初始值为1while (deno <= 100){i++;n = 1 / deno;if (i % 2 == 0)//如果为偶数项则改变正负号{n = -n;}sum += n;deno++;}printf("%.9lf", sum);return 0;
}
运行结果:
0.688172179
题目:投票结果
代码:
#include<string.h>
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
MessiResult:
Messi:2
Mbappe:1
Haaland:1
题目:指向结构体变量的指针
代码:
#include<stdio.h>
#include<string.h>
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
这篇关于2023-12-16 课后练习(复习+结构体练习)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!