c - 为什么这个等式不像我期望的那样循环?

标签 c arguments pass-by-value

我正在尝试根据百分比计算 Markdown 。如果我手写出来,它会像下面的方程式一样出现,一个简单的 x = x - (10% of x) 或 new_price = old_price - (10% of old_price)。所以 100 会变成 90,90 会变成 81,等等。我认为。我不确定我是不是在胡思乱想,但是当我运行它时,它只是永远循环“90”作为输出。

#include <stdio.h>
#include <math.h>


int pricedecrease(int x)
{
    x = x - (x / 10.0);
    return  x;
}

int main(void)
{
    int price = 100;

    while(price > 3)
    {
        printf("%d\n", pricedecrease(price));
    }
}

最佳答案

您需要在循环中更新价格变量。调用 pricedecrease 函数不会修改 price 变量。

#include <stdio.h>
#include <math.h>


int pricedecrease(int x)
{
    x = x - (x / 10.0);
    return  x;
}

int main(void)
{
    int price = 100;

    while(price > 3)
    {
        printf("%d\n", price);
        price = pricedecrease(price); // <- need to update price variable
    }
}

关于c - 为什么这个等式不像我期望的那样循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209277/

相关文章:

Perl GetOpt::Long 带有可选参数的多个参数

javascript - 两个变量在 Node.js 中使用 require (引用问题)引用相同的 config.js 文件

c - 关于 char 的通用指针和严格别名

c - 链表,从前面删除节点?

arguments - 如何在 Dart 中访问或迭代参数

python - 无法使用 "#!/usr/bin/env python"将参数传递给 python

c - 为什么结构体初始化后其值会被破坏?

c - 为包含灵活数组成员的结构动态分配内存

java - 为什么 Java 不提供简单的交换功能?

c++ - C++ 中的指针和函数