如何将一个整数除以另一个大于零的数并给出余数

How to divide an integer number with another number greater than zero and give remainer

本文关键字:大于 另一个 余数 整数 一个      更新时间:2023-10-16

我的程序在两个数字都为正时执行其功能,但当其中一个数字为负时则不执行。

#include <iostream>
using namespace std;
int main(){
    int a,b;
    b > 0;
    cin >> a >> b;
    int d;
    d = a/b;
    int r;
    r = a%b;
    cout << d << " " << r << endl;
}
在我的程序中:
  • 32/6 = 5 2(除数和余数)
  • -32/6 = -5 -2(除数和余数)

程序应该做什么:

  • 32/6 = 5 2(除数和余数)
  • -32/6 = -6 4(除数和余数)

您正在查找modulus操作符,'%'

int a = 5 % 2;
cout << a << endl;

模数运算符返回第一个值除以第二个值的余数。

我自己搞定了。对于任何需要这样一个程序的人,它在这里:

#include <iostream>
using namespace std;
int main(){
    int a,b;
    cin >> a >> b;
    int d = a/b;
    int r = a%b;
    if (r < 0){
        d = d-1;
        int s = d*b;
        r = -s+a;
    }
    cout << d << " " << r << endl;
}
相关文章: