实验二 C语言分支与循环基础应用编程
实验任务1——抽学号
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
#define N1 397
#define N2 476
#define N3 21
int main() {
int cnt;
int random_major, random_no;
srand(time(NULL)); // 以当前系统时间作为随机种子
cnt = 0;
while(cnt < N) {
random_major = rand() % 2;
if(random_major) {
random_no = rand() % (N2 - N1 + 1) + N1;
printf("20248329%04d\n", random_no);
}
else {
random_no = rand() % N3 + 1;
printf("20248395%04d\n", random_no);
}
cnt++;
}
}
问题1
rand()
生产一个随机数% (N2 - N1 + 1)
将随机数限制在0
到N2 - N1
(班级人数)之间,最后加上N1
组成学号。
问题2
同上,此时班级人数为N3
,加上1
组成学号。
问题3
随机从两个班级中抽取学号。
实验任务2——一元二次方程
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c;
double delta, p1, p2; // 用于保存中间计算结果
while (scanf_s("%lf%lf%lf", &a, &b, &c) != EOF) {
if (a == 0) {
printf("a = 0, invalid input\n");
continue;
}
delta = b * b - 4 * a * c;
p1 = -b / 2 / a;
p2 = sqrt(fabs(delta)) / 2 / a;
if (delta == 0)
printf("x1 = x2 = %.2g\n", p1);
else if (delta > 0)
printf("x1 = %.2g, x2 = %.2g\n", p1 + p2, p1 - p2);
else {
printf("x1 = %.2g + %.2gi, ", p1, p2);
printf("x2 = %.2g - %.2gi\n", p1, p2);
}
}
}
实验任务3——模拟信号灯
#include <stdio.h>
int main()
{
char a;
while (scanf_s("%c", &a) != EOF) {
getchar();
if (a == 'r') {
printf("stop!\n");
}
else if (a == 'y') {
printf("wait a minute\n");
}
else if (a == 'g') {
printf("go go go\n");
}
else {
printf("something must be wrong...\n");
}
}
}
实验任务4——记账
#include <stdio.h>
int main() {
printf("输入今日开销:\n");
double input, sum, max, min;
max = 0;
min = 20000;
sum = 0;
while (1) {
scanf_s("%lf", &input);
getchar();
if (input == -1) {
break;
}
if (input < min) {
min = input;
}
if (input > max) {
max = input;
}
sum += input;
}
printf("今日累计消费总额:%lf\n", sum);
printf("今日最高一笔开销:%lf\n", max);
printf("今日最低一笔开销:%lf\n", min);
}
实验任务5——三角形形状
#include <stdio.h>
int main()
{
int a, b, c;
while (scanf_s("%d%d%d", &a, &b, &c) != EOF) {
getchar();
if (a + b > c && b + c > a && a + c > b) {
if (a == b || b == c || a == c) {
if (a == b && b == c && a == c) {
printf("等边三角形\n");
}
else if (a * a + b * b == c * c || b * b + c * c == a * a || a * a + c * c == b * b) {
printf("等腰直角三角形\n");
}
else {
printf("等腰三角形\n");
}
}
else if (a * a + b * b == c * c || b * b + c * c == a * a || a * a + c * c == b * b) {
printf("直角三角形\n");
}
else {
printf("普通三角形\n");
}
}
else {
printf("不能构成三角形\n");
}
}
}
实验任务6——猜日期
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int num = (rand() % 30 + 1);
int input, min, max;
min = 1;
max = 30;
printf("从1-30中猜一个数");
for (int i = 0;i < 3;i++) {
printf("%d~%d:", min, max);
scanf_s("%d", &input);
if (input == num) {
printf("猜对了!");
return 0;
}
else if (input > num) {
printf("大了\n");
max = input - 1;
}
else {
printf("小了\n");
min = input + 1;
}
}
printf("答案是:%d", num);
}
标签:include,int,max,编程,else,printf,input,C语言,分支 From: https://www.cnblogs.com/cuo-ren/p/18454998