第三次上机实验记录

来源:互联网 发布:美团大数据平台 编辑:程序博客网 时间:2024/04/20 05:06

目标:
1. 掌握C语言基本运算符和表达式用法;
2. 预习选择和重复控制语句的用法.
任务1:假设整型变量 a 的值是 1,b 的值是 2,c 的值是 3,请判断各语句的值,写出执行结果,并作简短分析.
1) x = a ? b : c;
2) y = (a = 2) ? b + a : c + a; 
我编写的程序

#include<stdio.h>void main(){int a=1,b=2,c=3;                    int x,y;                            x=a?b:c;                            printf("x=a?b:c=%d\n",x);y=(a=2)?b+a:c+a;printf("y=(a=2)?b+a:c+a=%d\n",y);}

运行结果

分析:其中“x=a?b:c”即若X=a为真,,则把b的值赋给x,若不等于a,则把c的值赋给x.

任务2:假设整型变量a 的值是1 ,b 的值是2 ,c 的值是0 ,请判断各语句的值,写出执行结果,并作简短分析.
1) a && c
2) a || c &&b
3) a || c|| (a && b)
我编写的程序

#include<stdio.h>void main(){int a=1,b=2,c=0;int e,f,g,h,i;e=a&&c;f=a||c&&b;g=a||c||(a&&b);h=b&&c&&!a;i=a&&!((b||c)&&!a);printf("a&&c=%d\na||c=%d\na||b=%d\n",e,f,g);printf("b&&c&&!a=%d\na&&!((b||c)&&!a)=%d\n",h,i);}

运行结果

 分析:优先度"!> &&>||"

任务3. 写程序计算以下各个表达式的值。
说明: 程序头文件要添加 #include<math.h> 和 #include <conio.h>
 1)3 * (2L + 4.5f) - 012 + 44 
 2)3 * (int)sqrt(144.0) 
 3)cos(2.5f + 4) - 6 *27L + 1526 - 2.4L 
我编写的程序

#include<stdio.h>#include<math.h> #include <conio.h>void main(){float a=3*(2L+4.5f)-012+44;  int b=3*(int)sqrt(144.0);float c=cos(2.5f+4)-6*27L+1526-2.4L;printf("3*(2L+4.5f)-012+44=%f\n",a);printf("3*(int)sqrt(144.0)=%d\n",b);printf("cos(2.5f+4)-6*27L+1526-2.4L=%f\n",c);  }

运行结果

任务4:以下两个程序都能实现了“取两个数最大值”算法,理解并分析两个程序的不同.
写法一:
[cpp]view plaincopyprint?

double dmax (double x, double y) 

if (x > y) 

return x; 

else 

return y; 

int main() 

10 

11 double a,b; 

12 printf("Input 2 number:\n"); 

13 scanf_s("%lf %lf",&a,&b); 

14 printf("The max is:%f \n",dmax(a,b)); 

15 

.
写法二:

[cpp]view plaincopyprint?

16 double dmax (double x, double y); 

17 int main() 

18 

19 double a,b; 

20 printf("Input 2 number:\n"); 

21 scanf_s("%lf %lf",&a,&b); 

22 printf("The max is:%f \n",dmax(a,b)); 

23 

24 double dmax (double x, double y) 

25 

26 if (x > y) 

27 return x; 

28 if (x < y) 

29 return y; 

30 

运行结果

 

分析:第一种用了else函数。即当有两种情况时,只需写一种,另一种可以用else来代替。

5参考任务4,编写返回三个参数中最大的一个的程序,要求函数名为 double tmax(double, double, double),详细说明设计思路.
我的程序

#include<stdio.h> double dmax (double x, double y,double z); {  if (x > y && x > z)          return x;       if(y > x && y > z)     return y;  if(z > x && z > y)  return z;  return 0; }         int main()    {      double a,b,c;      printf("Input 3 number:\n");      scanf_s("%lf %lf %1f",&a,&b,&c);     printf("The max is:%f \n",dmax(a,b,c));    }

运行结果

分析:三个数时,不能用else语句。需依次来判断。

任务6写一个简单程序,它输出从10的整数,详细说明设计思路。
我的程序

#include<stdio.h>void main(){int i;i=1;while(i<=10){printf("%d\n",i);i++;}}

运行结果

分析:先设置循环变量i,使其初始值为1,使用while语句,让它循环到一个限定量。

任务7写一个简单程序,它输出从10到-10的整数,详细说明设计思路。
我的程序

#include<stdio.h>void main(){int i;i=-10;while(i<=10){printf("%d\n",i);i++;}}


运行结果

分析:输出-10-10的整数。即把初始值定为-10,即可。