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

如何修改C语言代码以展示欧几里得算法求GCD的全部计算步骤

需求可行性说明

该需求完全可以实现,无需改动原有核心计算逻辑,仅需在递归执行的关键节点增加步骤打印逻辑即可。

需要调整的核心修改点
  • 在GCD函数入口处增加打印,输出当前参与计算的两个整数值
  • 在a>b和a<b的分支判断位置,打印本次递归要执行的减法规则和新的调用参数
  • 在a==b的递归终止节点,打印终止提示和最终返回的结果
  • 可选补充:增加输入合法性校验,避免输入非正整数导致递归死循环
修改后的完整代码
#include <stdio.h>

int
GCD (int a, int b)
{
  // 打印当前调用参数
  printf("当前执行计算:GCD(%d, %d)\n", a, b);
  if (a == b)
    {
      printf("两数相等,触发递归终止条件,返回结果:%d\n", a);
      return a;
    }
  else
    {
      if (a > b) {
        printf("判定:%d > %d,执行规则:用大数减小数,调用GCD(%d - %d, %d)\n", a, b, a, b, b);
        return GCD (a - b, b);
      }
      else {
        printf("判定:%d < %d,执行规则:用大数减小数,调用GCD(%d, %d - %d)\n", a, b, a, b, a);
        return GCD (a, b - a);
      }
    }
}

int
main ()
{
  int a, b;
  printf("Please enter 2 numbers separated by a comma: ");
  scanf ("%d,%d", &a, &b);
  // 补充输入合法性校验
  if (a <= 0 || b <= 0) {
    printf("输入错误,请输入正整数\n");
    return 1;
  }
  printf ("\nGCD of %d and %d is %d", a, b, GCD (a, b));
  return 0;
}
运行效果示例

输入12,8时的输出如下:

Please enter 2 numbers separated by a comma: 12,8
当前执行计算:GCD(12, 8)
判定:12 > 8,执行规则:用大数减小数,调用GCD(12 - 8, 8)
当前执行计算:GCD(4, 8)
判定:4 < 8,执行规则:用大数减小数,调用GCD(4, 8 - 4)
当前执行计算:GCD(4, 4)
两数相等,触发递归终止条件,返回结果:4

GCD of 12 and 8 is 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:24:10