当我输入一个浮点数(例如48.3)时,显示的结果是48.00而不是48.30。每当我尝试输入空格的字符串时,程序立即结束。我需要帮助,如何解决这个问题?
int integer;
char a[50];
float fnum;
char b[50];
printf("Please enter an integer : ");
scanf("%s",&a);
integer = atoi(a);
printf("\nPlease enter a floating-point number : ");
scanf("%s", &b);
fnum = atoi(b);
printf("Output : \n");
printf("%i + %.2f = %.2f \n", integer,fnum,(integer+fnum));
printf("%i - %.2f = %.2f \n", integer,fnum,(integer-fnum));
printf("%i * %.2f = %.2f \n", integer,fnum,(integer*fnum));
答案 0 :(得分:2)
您正在通过调用b
将字符串atoi
转换为整数。您想将其转换为浮点数,因此请使用atof
:
fnum = atof(b);
答案 1 :(得分:1)
atoi返回一个int。 atof返回一个浮点数。
int integer;
char a[50];
float fnum;
char b[50];
printf("Please enter an integer : ");
scanf("%s",&a);
integer = atoi(a);
printf("\nPlease enter a floating-point number : ");
scanf("%s", &b);
fnum = atof(b);
printf("Output : \n");
printf("%d + %.2f = %.2f \n", integer,fnum,(integer+fnum));
printf("%d - %.2f = %.2f \n", integer,fnum,(integer-fnum));
printf("%d * %.2f = %.2f \n", integer,fnum,(integer*fnum));