当前位置:文档之家› 大连理工c语言第一次上机作业参考答案

大连理工c语言第一次上机作业参考答案

第一次上机作业参考答案:
1.大写字母转换成小写字母
从键盘输入一个大写英文字母,输出相应的小写字母。

例:输入G
输出g
#include <stdio.h>
void main()
{ char c;
c=getchar();
if(c>='A' && c<='Z')
c+=32;
putchar(c);
}
2.求平方根
输入1 个实数x,计算并输出其平方根(保留1 位小数)。

例:输入17
输出The square root of 17.0 is 4.1
#include <stdio.h>
#include <math.h>
void main()
{ float x,root;
scanf("%f",&x);
if(x>0)
root=sqrt(x);
else
printf("Input Error!\n");
printf("The square root of %.1f is %.1f\n",x,root);
}
3.Temperature Conversion
Design a program which converts from degrees Fahrenheit temperature to degrees Celsius temperature.
c = 5/9(f-32)
a)Input Fahrenheit temperature will be type float.
b)Display the temperatures with 2 places of precision
#include <stdio.h>
void main()
{ float f,c;
scanf("%f",&f);
c = 5.0/9*(f-32);
printf("Fahrenheit %.2f is equal to Celsius %.2f\n",f,c);
}
4. 计算旅途时间
输入2 个整数time1 和time2,表示火车的出发时间和到达时间,计算并输出旅途时间。

(有效的时间范围是0000 到2359,不需要考虑出发时间晚于到达时间的情况。

)
例:输入712 1411 (出发时间是7:12,到达时间是14:11)
输出The train journey time is 6 hrs 59 mins.
#include <stdio.h>
void main( )
{ int time1, time2, hours, mins;
scanf("%d%d", &time1, &time2);
mins=time2%100>time1%100?time2%100-time1%100:60+time2%100-time1%100;
hours=time2%100>time1%100?time2/100-time1/100:time2/100-1-time1/100;
printf("The train journey time is %d hrs %d mins.\n", hours, mins);
}
5. 数字加密
输入1 个四位数,将其加密后输出。

方法是将该数每一位上的数字加9,然后除以10 取余,做为该位上的新数字,最后将第1 位和第3 位上的数字互换,第2 位和第4 位上的数字互换,组成加密后的新数。

例:输入1257
输出The encrypted number is 4601
#include <stdio.h>
void main( )
{ int number, digit1, digit2, digit3, digit4, newnum;
scanf("%d", &number);
digit1=number/1000;
digit2=number%1000/100;
digit3=number%1000%100/10;
digit4=number%1000%100%10;
digit1=(digit1+9)%10;
digit2=(digit2+9)%10;
digit3=(digit3+9)%10;
digit4=(digit4+9)%10;
newnum=digit3*1000+digit4*100+digit1*10+digit2;
printf("The encrypted number is %d\n", newnum);
}
思考题:你能否编程找出谁做的好事?
有四位同学中的一位做了好事,不留名,表扬信来了之后,校长问这四位是谁做的好事。

⏹A说:不是我。

⏹B说:是C。

⏹C说:是D。

⏹D说:他胡说。

已知三个人说的是真话,一个人说的是假话。

现在要根据这些信息,找出做了好事的人。

#include <stdio.h>
void main()
{ char thisman;
int sum,found=0;
for(thisman='A';thisman<='D';thisman++)
{ sum=(thisman!='A')+(thisman=='C')
+(thisman=='D')+(thisman!='D');
if(sum==3)
{ printf("%c did it!\n",thisman);
found=1;
break;
}
}
if(found==0)
printf("Not found!\n");
}。

相关主题