当我输入1英里时,我的程序不能正确输出

#include <stdio.h>

int main(void)
{
int kilometers;

int miles;

printf("\n");
printf("Please enter the distance in miles: ");
scanf("%d", &miles);
printf("\n");

kilometers = 1.52 * miles;

printf("%d miles is equal to ", miles);

printf("%d kilometers", kilometers);
printf("\n\n");

return 0;

}

当我输入1英里时,它应该输出到1.52公里,但给我1公里

最佳答案

如注释中所述,您使用的是int而不是floatdouble,因此无法获得所需的精度。此外,英里到公里的转换也不正确;每1.60934英里有1公里。

#include <stdio.h>

int main(void) {

double kilometers;
double miles;

printf("\nPlease enter the distance in miles: ");
scanf("%lf", &miles);
printf("\n");

kilometers = 1.60934 * miles;

printf("%.2lf miles is equal to ", miles);
printf("%.2lf kilometers\n\n", kilometers);

return 0;

}

关于c - 程序输出不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57779741/

10-09 17:00