1. 程式人生 > >簡單編寫向下取整 - C++描述

簡單編寫向下取整 - C++描述

簡單編寫向下取整 - C++描述


  • 問題提出

在很多語言中,簡單的/符號可以很快幫我們取整,那麼如何更基本地實現這個小演算法呢?

  • 基本思路

如果有兩個正整數a和b,那麼計算a/b=x 就等價於計算:

a ÷ b = m a x { x |
b x a }

a ÷ b = m a x { x | b x < a + 1 }

我們著重理解第二個式子,並對其進行程式碼編寫。

  • 程式碼編寫
#include <iostream>
using namespace std;
int main(){//function: a/b

    int a,b;  //the two numbers a,b
    cin>>a>>b;

    int c=1; //the constant
    int tmp=a+1;
    int ans=0; //record the answer

    for(;tmp-b>0;){
        tmp=tmp-b;
        ans+=1;
    }

    cout<<ans<<endl;
    return 0;
}