C语言程序设计笔记—scanf、算术运算符的使用案例
例1 从键盘输入一个时间量(单位是分钟),计算该时间量相当于几小时几分钟。
(1)源程序代码
#include <stdio.h>
#include <stdlib.h>int main()
{int a,b,c;printf("请输入一个时间量(单位是时间):");scanf("%d",&a);b=a/60;c=a%60;printf("%d分钟相当于%d小时%d分\n",a,b,c);return 0;
}
(2)运行效果图
例2 从键盘输入一个四位正整数,将它每一位上的数分离出来。
(1)源程序代码
#include <stdio.h>
#include <stdlib.h>int main()
{int A,yi,san,wu,qi;printf("请输入一位四位正整数:");scanf("%d",&A);yi=A/1000;san=A%1000/100;wu=A%1000%100/10;qi=A%10;printf("%d每一位上的数分别是:\n千位:%d 百位:%d 十位:%d 个位:%d\n",A,yi,san,wu,qi);return 0;
}
(2)运行效果图
例3 从键盘输入一个实数(其中小数位数不少于3位),编程将该实数进行四舍五入,保留2位小数。
(1)源程序代码
#include <stdio.h>
#include <math.h>int main()
{double A,B;printf("请输入一位小数位数不少于3位的实数:");scanf("%lf",&A);B=(float)(round)(A*100)/100;printf("对%lf进行四舍五入(保留两位小数)结果是:%lf\n",A,B);return 0;
}
(2)运行效果图
例4 从键盘输入三角形的三条边长,求三角形的面积。
提示:求x的开方值的数学库函数是 sqrt(x),使用时需包含头文件 #include <math.h>
(1)源程序代码
#include <stdio.h>
#include <math.h>int main()
{int a,b,c;double x,s;printf("请键盘输入三角形的三边:");scanf("%d,%d,%d",&a,&b,&c);x=(a+b+c)/2;s=sqrt(x*(x-a)*(x-b)*(x-c));printf("三角形的面积是:%lf\n",s);return 0;
}
(2)运行效果图
例5 从键盘输入3个数字字符,将它们分别转换为对应的整数值(即字符’0’转换为整数0,字符’1’转换为整数1,依次类推),然后求3个整数的平均值。
(1)源程序代码
#include <stdio.h>
#include <math.h>int main()
{char a,b,c;int x,y,z;double aver;printf("请输入3个数字字符:");scanf("%c,%c,%c",&a,&b,&c);x=a-48,y=b-48,z=c-48;aver=(x+y+z)/3;printf("平均值:%lf\n",aver);return 0;
}
(2)运行效果图