2014-02-20 62 views
2

compsci新手在這裏。我應該編寫2個用戶輸入的值,並且不用*和/運算符將它們相乘並分開。如何在不使用除法運算符的情況下分割兩個整數?

我已經找到了如何繁殖,但不能分割......

//Multiplication 
    cin >> digit1; 
    cin >> digit2; 

    float product = 0; 

    for (int i = 0; i < digit2; i++) product = product + digit1; 
    cout << product << endl; 

    return 0; 

爲師我不完全相信......

cin >> digit1; 
    cin >> digit2; 

    float quotient = 0; 

    //Enter Division operation 
    cout << quotient << endl; 
    return 0; 

感謝您的幫助!

+0

'digit1 *(digit2^-1)'也許。 –

+1

你可以用非常相似的方式解決這個問題,以解決乘法問題。如果乘法只是快速加法,那麼除法是什麼?不要計算一個產品,但要考慮到零和計算迭代。 – pstrjds

+0

@MattBall嗯,我不知道我被允許使用^操作符... – Moojave

回答

3

對於鴻溝,我們可以做這樣的事情(下面將digit2/digit1):

int movingNum = 0; 
int i = 0; 
while(movingNum < digit2){ 
    // This is the counter of how many times digit1 goes into digit2, increment it 
    // because the running sum is still less than digit2 
    i++; 

    // increment the moving sum by digit1 so that it is larger by digit1 moving through 
    // the next iteration of the loop 
    movingNum += digit1; 
} 

cout << "digit1 goes into digit2 " << i << " times."; 

對於digit1/digit2:

int movingNum = 0; 
int i = 0; 
while(movingNum < digit1){ 
    // This is the counter of how many times digit2 goes into digit1, increment it 
    // because the running sum is still less than digit1 
    i++; 

    // increment the moving sum by digit2 so that it is larger by digit2 moving through 
    // the next iteration of the loop 
    movingNum += digit2; 
} 

cout << "digit2 goes into digit1 " << i << " times."; 

這些顯然是對整數除法,如果兩個輸入不等分,則會有餘數。這剩餘部分可以在上面的循環後進行計算:

int remainder = movingNum - digit2; 

如果你是真正的尋找一個浮點答案/結果,這將是一個完全不同的答案。

+0

It不適合我,我不斷得到輸出爲0 – Moojave

+0

@Moojave是digit1大於digit2 ???如果它的回答應該是0.是否要求有數字1 /數字2或數字2 /數字1?乘法很容易,劃分需要了解訂單! – trumpetlicks

+0

Digit 1/Digit 2 – Moojave

相關問題