编程数据类型

Mat*_*hew 7 c types primitive-types

我正在努力学习C并且已经提出了以下小程序.

#include "stdafx.h"

void main()
{
    double height = 0;
    double weight = 0;
    double bmi = 0;

    printf("Please enter your height in metres\n");
    scanf_s("%f", &height);
    printf("\nPlease enter your weight in kilograms\n");
    scanf_s("%f", &weight);
    bmi = weight/(height * height);
    printf("\nYour Body Mass Index stands at %f\n", bmi);
    printf("\n\n");
    printf("Thank you for using this small program.  Press any key to exit");
    getchar();
    getchar();
}
Run Code Online (Sandbox Code Playgroud)

该程序编译完美,但程序返回的答案没有意义.如果我输入1.8的高度和80的重量,bmi就像1.#NF00这没有意义.

我究竟做错了什么?

Ric*_*III 11

scanf与a一起使用时double,必须使用说明%lf符,因为指针不会被提升scanf.

有关详细信息,请阅读以下问题: 为什么scanf()需要"%lf"才能获得双打,而printf()只需"%f"就可以了?


Did*_*set 10

scanf(和scanf_s)格式%f需要指向类型的指针float.

只需更改您heightweight变量的类型float即可解决此问题.

  • IMO,这种事情足以完全避免`scanf()` - 通过指针返回值是非常无情的.将输入作为字符串输入并将其提供给`atof()`. (2认同)