簡體   English   中英

= 運算符在這里的用途是什么?

[英]What is the usage of the = operator here?

以下是我在階乘中查找尾隨零數的解決方案,它有效,我發布它是為了了解算法的工作原理,即 n 除以 5 ^ i 的商之和,其中 i>0 .

#include <cmath>
long zeros(long n) {
    long sum = 0;
    for (int i = 1;; ++i) {
        int m = n / pow(5, i);
        if (m == 0)
            break;
        else sum += m;
    }
    return sum;
}

我看到了這個解決方案,它使我對=運算符的使用感到困惑。 =5在這種情況下是什么意思?

long zeros(long n) {
    long result = 0;
    while(n)
        result += n/=5;
    return result;
}

表達式result += n/=5等價於首先將n的值更新為n/5 ,然后將result的值更新為result + n ,其中n現在為n/5

// result += n/=5 is same as doing
n = n / 5;
result = result + n;

這里的/=類似於+= ,因為n/=5等價於n = n/5

將值或變量分配給變量,即 m = n 表示如果 n 為 15,則 m 將是 n 的值,即 15

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM