2012-07-26 76 views
7

我正在努力学习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(); 
} 

程序编译完美,但程序返回的答案没有意义。如果我输入高度为1.8,体重为80,那么bmi就像1.#NF00,这是没有意义的。

我在做什么错?

+10

是不是双打'%lf'?在任何情况下,[你不应该使用'void main'。](http://stroustrup.com/bs_faq2.html#void-main) – chris 2012-07-26 14:42:25

+0

@chris好东西知道。我总是被教导,'void main'是用于C,'int main'用于C++。我想知道新C/C++程序员做这件事的习惯是从哪里来的。 – Darthfett 2012-07-26 18:53:35

+0

@Darthfett,我认为有几本书使用'void main'。我想这就是所有这些都是从那里传来的。 – chris 2012-07-26 18:58:25

回答

10

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

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

+0

谢谢:)完美的工作!我使用了%f,因为我在下面的教程中使用了%f作为double。 – Matthew 2012-07-26 14:45:48

+1

@Matthew我认为现在是时候获得一个新的教程。 – 2012-07-26 14:47:22

+0

我想是这样的:再次感谢:) – Matthew 2012-07-26 15:14:21

4

我觉得在scanf_s大成问题,你中省略3挡的说法,这是在字节缓冲区的大小。请尝试以下操作:

scanf_s("%lf", &valueToGet, sizeof(double)); 
+1

嗯,他没有在这里扫描'char',你知道 – 2012-07-26 14:46:47

+0

是的,我知道这个我只是一个例子来显示需要什么3-rd参数,这是我从msdn快速获取的,因为我试图快速回答我没有根据给定的任务调整这个例子,对不起)) – 2012-07-26 14:49:35

+0

大概你在谈论'scanf_s',但你写了'scanf'?格式说明符也是错误的。请修正错误或删除答案。 – 2012-07-26 14:51:26

3

的scanf()函数和printf(的缺点)是它需要非常严格的格式,控制线和参数之间的任何不匹配可能会导致剧烈的错误,让您的输入或输出不作任何一点意义。这个错误通常是由初学者做出的。

2

如果您使用%f格式说明符,则必须使用float数据类型而不是double。

0

的问题是因为:

format '%f' expects argument of type 'float*', but argument 2 has type 'double*' 

有两种方式来处理这个问题:

  1. 无论是变量应该是float

    double height = 0; --> float height = 0; 
    double weight = 0; --> float weight = 0; 
    double bmi = 0;  --> float bmi = 0; 
    
  2. format specifier应对应于double

    scanf_s("%f", &height); --> scanf_s("%lf", &height); 
    
    scanf_s("%f", &weight); --> scanf_s("%lf", &weight); 
    
    printf("\nYour Body Mass Index stands at %f\n", bmi); 
                  | 
                  V 
    printf("\nYour Body Mass Index stands at %lf\n", bmi);