Code::Blocks环境下C++圆参数计算函数代码可编译但结果错误求助
代码问题定位与修正
现存错误点
- 输出环节未调用函数
main函数中打印半径、周长、面积的代码,直接将函数名传入输出流,没有加括号传入参数执行调用逻辑,此时输出的是函数的内存地址,不是计算结果。对应问题代码:cout << "Circle's radius is: " << radius << endl;cout << "Circle's circumference is: " << circumference << endl;cout << "Circle's area is: " << area << endl; - 圆面积公式书写错误
面积函数内的计算逻辑为pow(PI*radius,2),等价于(π×r)²,不符合圆面积πr²的数学定义,计算结果偏差较大。 - 函数参数设计冗余
原radius函数定义要求传入5个参数,但函数内部完全没有使用前四个坐标参数,仅将传入的distance参数直接返回,属于无效的参数传递。 - 无用头文件引用
代码中引入的<cctype>没有任何对应功能调用,可直接删除减少编译冗余。
修正后可正常运行的代码
#include <iostream> #include <cmath> #include <iomanip> using namespace std; const double PI = 3.1416; double distance(double, double, double, double); double radius(double); double circumference(double); double area(double); int main() { double x1, y1, x2, y2; cout << fixed << showpoint << setprecision(2); cout << "Enter the center X and Y coordinate of a circle (in that order with a space in between): "; cin >> x1 >> y1; cout << "Enter another X and Y coordinate in the same circle (in that order with a space in between): "; cin >> x2 >> y2; double line_dist = distance(x1, y1, x2, y2); double r = radius(line_dist); cout << "Circle's radius is: " << r << endl; cout << "Circle's circumference is: " << circumference(r) << endl; cout << "Circle's area is: " << area(r) << endl; double diameter = 2 * r; cout << "Circle's diameter is: " << diameter << endl; return 0; } double distance(double x1, double y1, double x2, double y2) { return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } double radius(double line_dist) { return line_dist; } double circumference(double r) { return 2 * PI * r; } double area(double r) { return PI * pow(r, 2); }
内容的提问来源于stack exchange,提问作者sticks_
相关产品推荐
相关产品推荐

