【问题标题】:Why is this only returning whole numbers when i used double throughout?为什么当我始终使用 double 时这只返回整数?
【发布时间】:2021-02-24 10:38:32
【问题描述】:

只是想知道为什么这个面积计算代码只返回整数,尽管我一直使用 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。谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

这里:

piCalc(double radi){

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

double piCalc(double radi){

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多