为什么当我一直使用double时,这只会返回整数?

只是想知道为什么这个面积计算代码只返回整数,即使我一直使用 double 。

#include <iostream>

#define pi 3.14

piCalc(double radi) {
  double result;
  result = (radi * radi) * pi;
  return result;
}

int main() {
  double radius;
  std::cout << "Welcome to the circle area calculator. Please enter your radius"
            << std::endl;
  std::cin >> radius;
  std::cout << "your answer is " << piCalc(radius) << std::endl;
  std::cout << "thankyou for using the area calculator" << std::endl;
}

即使我输入一个浮点数,例如 5.3,我仍然只返回 88,而它应该是 88.25。谢谢。

回答

这里:

piCalc(double radi){

您缺少返回类型。这不是有效的 C++。在(古代?)C 中,您可以省略返回类型并int假设。一些编译器仍然允许将其作为非标准扩展。使返回类型double

double piCalc(double radi){

通常,您需要注意编译器扩展。例如,gcc 的默认设置相当宽松,并且编译了大量不应该根据标准 C++ 的代码。-pedantic选项可以帮助发现编译器特定扩展的这种不受欢迎的使用。

  • non-ancient gcc versions don't let you do this unless you specifically use `-fpermissive` https://gcc.godbolt.org/z/MfK3sW

以上是为什么当我一直使用double时,这只会返回整数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>