如何将一个整数除以另一个大于零的数并给出余数
How to divide an integer number with another number greater than zero and give remainer
我的程序在两个数字都为正时执行其功能,但当其中一个数字为负时则不执行。
#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;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 强制一个字符串大于另一个字符串
- 是否有一种方法可以正确地比较一个float值是否大于/小于另一个
- 如何将一个整数除以另一个大于零的数并给出余数