【问题标题】:C double type and resultsC double 类型和结果
【发布时间】:2021-05-15 16:46:32
【问题描述】:

所以我仍在使用 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));
}

这是输出:

输入任意数为平方:21 0.000000 0.000000 的平方:

所以,我不明白为什么它在编译完全正常并且语义看起来连贯的情况下返回零。 如果您不深入了解,我将不胜感激,因为我认为它可以简单地解释(我还是很新的^^')

【问题讨论】:

  • 请不要图片。将代码/输出作为文本发布。
  • 使用%lf 而不是%d
  • @Ghassen:这不是重点。 Images of code are not permitted.
  • 对于double,您必须使用%lf,而不是%f
  • 打开你的编译警告,你的编译器可能会告诉你格式说明符错误,以及void main()

标签: c function types double


【解决方案1】:

当我尝试编译这段代码时,我收到警告:

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.

这些都与问题非常相关。这些是使用-Wall 使用clang 生成的,但GCC 和其他编译器具有类似的方法。 clang 非常有帮助、具体且非常善于解释潜在的修复。

纠正这些问题并清理代码会导致:

#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;
}

现在一切都按预期进行。

【讨论】:

  • 非常感谢您的详细解释。看起来我将停止使用我的 Atom 扩展。只是一个简短的问题, void main 和 int main 有什么区别?从理论上讲,我发现它可以正常工作,并且我的 Atom 在将 %f 更改为 %lf 后正常执行它(同时保持 void main)
  • @Ghassen main() 函数必须返回一个 int 值,它向您的系统返回一个数字,按照惯例返回 0 表示程序正确退出,没有任何错误(并且是一个非零值表示发生了一些异常情况,例如错误,并且程序没有按原计划完成)。尽管工作,但 void main() 是完全错误的。 stackoverflow.com/questions/204476/…
  • 如果您致力于学习 C,好消息是该语言本身并没有那么复杂,但它确实有重要的细微差别和警告,因为这取决于程序员关注他们的内容'重新做。就像如果你没有正确操作汽车会从悬崖上驶下一样,如果你不经意地要求它这样做,C 会做各种各样的事情,这些事情会让程序严重崩溃。因此,请密切注意任何和所有编译器警告,甚至在可用的情况下使用“将警告视为错误”的标志。
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 2014-04-03
  • 2020-02-16
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多