导航

实验三

Posted on 2021-04-15 22:17  布鲁布鲁鲁  阅读(44)  评论(2)    收藏  举报

1.

// 生成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() % 100; // 生成一个0~99之间的随机整数
printf("%3d", x);
}

printf("\n");

return 0;
}

 

 

2.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5

int main() {
int luckday, x, i;
int add();

srand(time(0));
luckday = rand() % 32;
printf("猜猜2021年5月哪一天会是你的luckday\n开始喽,你有三次机会,猜吧(1~31):");
for(i=1;i<=3;i++){
scanf("%d",&x);
if(x>luckday)
printf("你猜的日期晚了,luck day 悄悄溜到前面啦\n再猜(1~31):");

else if(x<luckday)
printf("你猜的日期早了,luckday还没到呢\n再猜(1~31)");
else
break;
}
if(i>3)
printf("次数用完啦。偷偷告诉你:5月,你的luckday是%d号",luckday);



system("pause");
return 0;
}

 

 3.

#include<stdio.h>
int main()
{
long a,b,m,n;
while(printf("Enter your number:"),scanf("%ld", &a)!=EOF)
{
m = a;
n = 1;
while (m /= 10)
n *= 10;
while (a)
{
if ((b = a / n) % 2 != 0)
(m *= 10) += b;
a %= n;
n /= 10;
}
printf("New number is:%ld\n", m);
}
return 0;
}

 

 4.

#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;
}


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)
{
if(n==1)
return 1;
else if(n==2)
return 0.5;
else
return fun(n-1)-(fun(n-1))/n+(fun(n-2))/n;
}

 

 6.

#include<math.h>
#include<stdio.h> 
int isPrime(int n);
int main()
{
    int m=0,n,col=1;
    for(n=101;n<200;n++)
    {
        if(isPrime(n)==0)
        {
            printf("%d ",n);
            col++;
            m++;
            while(col>5)
            {
                printf("\n");
                col=1;
            }
        }
    }
    printf("\n");
    printf("100~200之间共有%d个素数",m);
    return 0;
}
int isPrime(int n)
{
    int i;
    for (i = 2; i <= sqrt(n); i++)
    {
        if (n%i == 0)
            return 1;
    }
    return 0;