C语言浮点数的表示

c语言中出现浮点数计算时,然而定义数据类型是int的情况下,解决方案有两种:

方案一:改数据类型为 double,注意输出时,格式化需将%d改成%f

#include <stdio.h>

int main()
{
	printf("请分别输入身高的英寸和英尺,\n"
	"如输入\"5,7\"表示5英尺7英寸:");
	
	const double S = 0.3048;
	double foot;
	double inch;
	
	scanf("%lf,%lf",&foot,&inch);
	
	printf("身高是%f米",((foot+inch/12)*S));
	
	return 0;

方案二:将在计算的值变成小数(如12→12.0),注意输出时,格式化需将%d改成%f

#include<stdio.h>

int main()
{
	printf("请分别输入身高的英尺和英寸,\n"
	"如输入\"5,7\"表示5英尺7英寸:");
	
	const double S = 0.3048;
	int foot;
	int inch;
	
	scanf("%d,%d",&foot,&inch);
	printf("身高是%f米。\n",((foot+inch/12.0)*S));
	
	return 0;	
	

猜你喜欢

转载自blog.csdn.net/qq_39711485/article/details/112061679
今日推荐