c - 如何根据输入的数字将答案设为 float 或整数?

标签 c floating-point integer temperature

目前正在做一项作业,但有点卡住了。我们要将温度从摄氏度转换为华氏度。如果答案是小数,则最终答案应输出 float ;如果答案是整数,则最终答案应输出整数。我已将其设置为给我 float ,但是当我输入一个数字(例如“98.6”)时,我会得到 37.00000 而不是 37。我已经花了几个小时试图独自对抗它,但我已经没有主意了。感谢您的帮助!

int main(void)
{
    float ftemp;
    float ctemp;    

        printf ("Enter a temperature in Fahrenheit: ");
    scanf ("%f", &ftemp);
    ctemp = (100.0 / 180.0) * (ftemp - 32);
    printf ("In Celsius, your temperature is %f!\n", ctemp);

    return 0;
}

最佳答案

确实没有像您所描述的那样的好方法。听起来您真正想要的是更好的字符串格式。尝试在 printf 中使用 %g 而不是 %f(根据 this 帖子)。

例如

printf ("In Celsius, your temperature is %g!\n", ctemp);

现在,如果您一心想要让它使用整数,那么您可以得到的最接近的是:

int main(void)
{
    float ftemp;
    float ctemp;
    int   ctempi;    

    printf ("Enter a temperature in Fahrenheit: ");
    scanf ("%f", &ftemp);
    ctemp = (100.0 / 180.0) * (ftemp - 32);
    ctempi = (int)ctemp;
    if(ctemp == ctempi) {
         printf("In Celsius, your temperature is %d\n", ctempi);
    } else {
         printf ("In Celsius, your temperature is %f!\n", ctemp);
    }

    return 0;

}

关于c - 如何根据输入的数字将答案设为 float 或整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792384/

相关文章:

自定义 float 加法,实现数学表达式 - C

c - SW 浮点实现的方法有哪些?

c++ - float 的四舍五入

java - 将数组元素从字符串转换为整数

c - 使用 Go 和 OpenCV 读取/写入图像中的 ICC 配置文件

bash 脚本可以从它作为参数的 C 可执行文件访问信息吗?

c - 无法解决错误 : control reaches end of non-void function

c++ - fscanf C++ 等价物

ios - 如何在 Swift 中将大于 Int.max 的浮点值转换为 Int

php - 大整数乘积差分算法