C实验参考答案(湖北民族学院计算机c语言课后习题答案).
实验二 基本数据类型、运算符及表达式
1. 分析以下程序,判断输出结果,然后上机运行程序验证结果。
(1)
# include
main( )
{ int sum = 1 ;
sum = sum +100 ;
printf("SUM = %d\n", sum);
}
输出结果为:101
(2) 改正后的程序为:
# include
main( )
{ char ch1 , ch2 ;
ch1 = 'b' ;//不能把字符串"b"赋给字符变量
ch2 = ch1 - 32 ;
printf("%c %d %c %d\n", ch2,ch2,ch1,ch1);
}
(3)
# include
main( )
{ int a = 10 , b =3 ;
printf("%d\n", (a = a - 1 , b + a , b + 2));
}
输出结果为5,(a = a - 1 , b + a , b + 2)作为一个逗号表达式。
(4)
# include
main( )
{
int a = 5 , b = 3 , c = 4 ;
a *= a += 3;
b = ++c ;
c = b++ ;
a = b +++ c ;
printf("\n%d,%d,%d", a , b , c);
}
输出结果为:11,7,5
(5)程序改正为:
# include
main( )
{
int a = 1 , b = 2 , c = 3 , logic ;
logic = a + b > c && b <= c ;
printf("logic = %d\n", logic);
logic = a >= b + c || b == c;
printf("logic = %d\n", logic);
logic =!(a < c) +b!=1 && (a + c)/2 ;
printf("logic = %d\n", logic);
}
输出结果为:
logic = 0
logic = 0
logic = 1
2. 以下程序可能有多处错误,请改正并调试运行程序。
(1)
# include
# include HIGH 10//改为:#include HIGH 10
main( )
{int a = 5 ; //可再定义一个变量b
HIGH *= HIGH ; //HIGH是宏名,不能被赋值,可改为:b=HIGH*HIGH;
printf("\n%d,%d", a , HIGH); //输出a,b的值
}
改正后的程序为:
# include
# define HIGH 10
main( )
{int a = 5 ,b;
b = HIGH*HIGH ;
printf("\n%d,%d", a , b);
}
输出结果为:5,100
(2)此程序功能为将输入的华氏温度转换成摄氏温度,公式为c = 5 / 9 ·(f–32 )。
# include
main( )
{ float c , f?;
scanf("%f", f)?;//输入时,变量要用&取地址
c = (5 / 9)· (F – 32)?; //5/9是为0的,要变成实数。F没有定义,定义的是f
printf((" F= %f , C = % f\n", f , c)?;//多了一个左括号
}
改正后的程序为:
# include
void main( )
{
float c,f;
scanf("%f", &f);
c=(5.0/9)*(f-32);
printf("F= %f,C = %f\n",f,c);
}
(3)此程序功能是求:y = 。
# include
# include
main( )
{ int a ;
double x , y ;
Scanf("%d%f", &a , &x)?;//scanf不能大写,x的类型是double,格式化字符应该用%ld
y = SIN(sqr(ax) + LN(a + x)?;//sin函数不能大写,sqr应该为sqrt,ax应为a*a,LN不是有效的函数名,要求自然对数用的是log(),另外括号不匹配
printf(" Y= %f \n", y)?;//y的类型是double,格式化字符应该用%ld
}
程序改正后为:
# include