实验3

//生成N个0~99之间的随机整数,并打印输出
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
int main() {
int x, n;
srand(time(0)) ;
for(n=1; n<=N; n++){
x = rand() % 31+1;
printf("%3d", x);
}
printf("\n");
return 0;
}

任务2
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 3
int main (){
int x,n;
srand(time(0));
x = rand() %31+1 ;
printf("猜猜2021年5月那一天会是你的Lucky day\n");
printf("开始喽,你有三次机会,猜吧(1—31):");
for(n=1;n<=3;n++){
int a;
scanf("%d",&a);
if(a==x){
printf("你猜中了\n");
break;
}
else if(a<x){
printf("你猜的日期早了,Lucky day还没到呢\n");
printf("再猜(1~31);");
}
else if(a>x){
printf("你猜的日期晚了,Lucky day悄悄溜到前面来啦\n");
printf("再猜(1—31):");
}
}
if (n==4)
printf("\n次数用完啦,偷偷告诉你:5月,你的Lucky day是%3d号",x);
else
printf("\n");
return 0;
}
![]()

任务3
#include<stdio.h>
#include<stdlib.h>
int main()
{
long int s,sum=0;
int m,x=1,n;
printf("Enter a number:");
scanf("%ld",&s);
do{
m=s%10;
s=s/10;
if(m%2!=0){
sum+=m*x;
x*=10;}
}while(s!=0);
printf("new number is:%ld\n",sum);
return 0;
}

任务4
// 一元二次方程求解(函数实现方式)
// 重复执行, 直到按下Ctrl+Z结束
#include <math.h>
#include <stdio.h>
// 函数声明
void solve(double a, double b, double c);
// 主函数
int main() {
double a, b, c;
printf("Enter a, b, c: ");
while(scanf("%lf%lf%lf", &a, &b, &c) != EOF) {
solve(a, b, c); // 函数调用
printf("Enter a, b, c: ");
}
return 0;
}
// 函数定义
// 功能:求解一元二次方程,打印输出结果
// 形式参数:a,b,c为一元二次方程系数
void solve(double a, double b, double c) {
double x1, x2;
double delta, real, imag;
if(a == 0)
printf("not quadratic equation.\n");
else {
delta = b*b - 4*a*c;
if(delta >= 0) {
x1 = (-b + sqrt(delta)) / (2*a);
x2 = (-b - sqrt(delta)) / (2*a);
printf("x1 = %.2f, x2 = %.2f\n", x1, x2);
}
else {
real = -b/(2*a);
imag = sqrt(-delta) / (2*a);
printf("x1 = %.2f + %.2fi, x2 = %.2f - %.2fi\n", real, imag, real, imag);
}
}
}

![]()
函数只能用一个返回值,不能有两个
任务5
#include <stdio.h>
double fun(int n); // ????
int main() {
int n;
double s;
printf("Enter n(1~10): ");
while(scanf("%d", &n) != EOF) {
s = fun(n); // ????
printf("n = %d, s= %f\n\n", n, s);
printf("Enter n(1~10): ");
}
return 0;
}
double fun(int n)
{int i=1,x=1;
double z=0,y=1;
if (n==1)
z=1;
else
{
while (x<n)
{i=i*(-1);
x=x+1;
y=y*x;
z=z+i/y;
}
z=z+1;
}
return z;
}
![]()

任务6
任务7
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
void printCharMan(int line, int col); // 函数声明
void printSpaces(int n); // 函数声明
int main() {
int line, col;
for(line=5, col=5; col<=60; col++) {
printCharMan(line, col);
Sleep(50); // 暂停50ms
system("cls"); // 清除屏幕
}
}
// 打印n个空格
void printSpaces(int n){
int i;
for(i=1; i<=n; i++)
printf(" ");
}
// 在第line行第col列打印一个字符小人
void printCharMan(int line, int col) {
int i, j;
// 打印line-1行空行
for(i=1; i<=line-1; i++)
printf("\n");
// 打印col-1个空格
printSpaces(col-1);
// 在第line行、第col列打印字符小人的头
printf(" O \n");
// 打印col-1个空格
printSpaces(col-1);
// 在第line行、第col列打印字符小人的身体
printf("<H>\n");
// 打印col-1个空格
printSpaces(col-1);
// 在第line行、第col列打印字符小人的腿
printf("I I\n");
}

浙公网安备 33010602011771号