简体   繁体   English

C 双型及结果

[英]C double type and results

So I am still training with C and noticed an unusal result while practicing functions.因此,我仍在使用 C 进行培训,并在练习功能时发现了一个不寻常的结果。

#include <stdio.h>
#include <math.h>
 void main()
 {


 printf("Input any number for square : ");
  double X;
  scanf("%f", &X);
  double square(double X);
  double n=square(X);
  printf("The square of %f %f:", X, n);
}
double square(double X)
{
return (pow(X,2));
}

Here's the output:这是 output:

Input any number for square: 21 The square of 0.000000 0.000000:为平方输入任意数字:21 0.000000 0.000000 的平方:

So, I am not understanding why is it returning zeros while the compilation is totally fine and the semantic looks coherent.所以,我不明白为什么它在编译完全正常并且语义看起来一致的情况下返回零。 I'll appreciate it if you don't go in depth because I think it can be explained simply (I'm still quite new ^^' )如果您不深入了解 go,我将不胜感激,因为我认为它可以简单地解释(我还是很新 ^^')

When I try and compile this code I get warnings:当我尝试编译此代码时,我收到警告:

square.c:3:2: warning: return type of 'main' is not 'int' [-Wmain-return-type]
 void main()
 ^
square.c:3:2: note: change return type to 'int'
 void main()
 ^~~~
 int
square.c:9:15: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
  scanf("%f", &X);
         ~~   ^~
         %lf
2 warnings generated.

These are both very relevant to the problem.这些都与问题非常相关。 These are generated with clang using -Wall , but GCC and other compilers have similar methods.这些是使用clang使用-Wall生成的,但是 GCC 和其他编译器具有类似的方法。 clang is very helpful, specific and very good about explaining potential fixes. clang对解释潜在的修复非常有帮助、具体且非常好。

Correcting those issues and cleaning up the code results in this:纠正这些问题并清理代码会导致:

#include <stdio.h>
#include <math.h>

// Declare functions before they are used whenever possible
double square(double X)
{
  // No reason for the extra brackets, just return ...
  return pow(X,2);
}

// main() is supposed to at least return int
int main()
{
  printf("Input any number for square : ");
  double x; // Variables typically lower-case, #define macros are upper-case
  scanf("%lf", &x);

  double n = square(x);

  printf("The square of %lf %lf:", x, n);

  // Formally indicate everything's good (no error = 0)
  return 0;
}

Where now everything works out as expected.现在一切都按预期进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM