You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言编程问题:计算结果恒为0,需实现输入半径求圆的面积与周长

问题分析与修复方案

你的代码计算结果始终为0的核心原因是**scanf读取变量时未传递地址**。C语言中,scanf需要通过指针修改外部变量的值,直接传入变量名会导致读取失败,Radius保持初始的0值,后续计算自然全部为0。

修正后的代码

#include <stdio.h>

int main(){

    double Radius, Circumference, Area, Pi = 3.1416;
    
    printf("Value of Radius:");
    scanf("%lf", &Radius);  // 关键修改:添加取地址符&
    
    Area = Pi * Radius * Radius;
    Circumference = 2 * Pi * Radius;
    
    printf("The area of the circle is %lf\n", Area);  // 用\n规范换行
    printf("The circumference of the circle is %lf\n", Circumference);
    
    return 0; 
}

关键说明

  • scanf("%lf", &Radius):&是取地址运算符,它会把Radius变量的内存地址传递给scanf,这样输入的值才能正确写入Radius中。
  • 原代码中的换行直接写在字符串里,改为\n是C语言的标准换行方式,兼容性更好。

现在运行代码,输入半径后就能正确计算并输出对应的面积和周长了。

内容的提问来源于stack exchange,提问作者Mark T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:45:55