c - 为什么输出是 36 而不是 24?

标签 c loops while-loop


#include <stdio.h>
#include <stdlib.h>

int f(int a, int b) {
    int a1 = a, b1 = b;

    while (a1 != b1)
        if (a1 < b1) a1 += a;
        else b1 += b;

    return a1;
}

int main() {
    printf("%d\n", f(12, 18));
    return 0;
} 

嗨,我不明白为什么结果是 36,有人可以解释一下吗?

最佳答案

让我们逐步完成:

f(12, 18) -> a = 12, b = 18
int a1 = a, b1 = b; -> a1 = 12, b1 = 18
while (a1 != b1) -> not equal -> do the loop
if (a1 < b1) a1 += a; -> a1 = 24
while (a1 != b1) -> not equal -> do the loop
if (a1 < b1) ... else b1 += b; -> b1 = 36
while (a1 != b1) -> not equal -> do the loop
if (a1 < b1) a1 += a; -> a1 = 36
while (a1 != b1) -> equal -> end the loop
return a1 -> return 36

关于c - 为什么输出是 36 而不是 24?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58751568/

相关文章:

c - 'itoa' : The POSIX name for this item is deprecated

c - 如何交换位位置值 12 34 56 78?

r - 循环总结观察大于R中的主题

python - Pandas:如果在循环内则滚动计数

c++ - 从单独的文件中读取每个字符?

c - 如何计算此循环完成后已运行了多少次?

c - 如何将一个 .c 文件中定义的结构填充到另一个 .c 中定义的函数中,而不将指针作为参数传递?

c++ - 通过 RS232 串行端口将数据发送到条码扫描器

c - while 循环内的 If 语句无法执行并退出程序

c# - 即使有 while 循环,Try/catch 函数也仅运行一次 C#