实验3 C语言分支语句、循环语句、函数综合应用编程-1
实验任务1
#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; printf("%3d", x); } printf("\n"); return 0; }

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

实验任务3
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<math.h> void getodd(long x); int main() { long num; printf("Enter a number: "); while(scanf("%ld",&num) != EOF) { getodd(num); printf("Enter a number: "); } return 0; } void getodd(long x) { long odd; int place, i; double system = 10; i = 0; odd = 0; while(x > 0) { place = x % 10; x = x / 10; if(place % 2 == 1) { odd = odd + place * pow(system,i); i++; } } printf("new number is : %ld\n", odd); }

实验任务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); } } }

不能,return不能返回两个值
实验任务4
#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; double num, den,s; num = 1; den = -1; s = 0; for(i = 1; i <= n; i++) { den = 0 - den * i; s = s + num/den; } return s; }

实验任务6
#include<stdio.h> #include<math.h> int isPrime(double x); int main() { int row, prime; double num; row = 0; prime = 0; for(num = 100; num <201; num++) { if(isPrime(num)) { row++; printf("%4.0lf", num); prime++; if(row % 5 == 0) printf("\n"); } } printf("101~200之间的素数个数是:%d\n", prime); return 0; } int isPrime(double x) { int i, num; num = x; for(i = 2; i <= sqrt(x); i++) { if(num % i == 0) return 0; } return 1; }

浙公网安备 33010602011771号