C ++,将较大的数字除以较小的数字,并用商和余数表示答案。 [英] C++, divide larger number by smaller number and express the answer in quotient and remainder.

查看:94
本文介绍了C ++,将较大的数字除以较小的数字,并用商和余数表示答案。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将较大的数字除以较小的数字并使用商和余数而不是分数或小数商表达答案。例如,如果我将7除以2,则答案将给出3作为商,1作为余数。将较大的数字除以较小的数字。



例如:

7/2 = 3 r 1

2/7 = 3 r 1



i到目前为止已完成此操作但我不知道我总是可以使用 if 来将更大的数字除以 else 声明。



how to divide larger number by smaller number and express answers using quotient and remainder rather than a fraction or decimal quotient. for example if i divide 7 by 2, answer would have been given 3 as a quotient and 1 as a remainder. Divide larger number by smaller.

example:
7 / 2 = 3 r 1
2 / 7 = 3 r 1

i have done this so far but i don't know to i can always divide larger number by smaller using if and else statement.

#include <iostream>
using namespace std;

int main() {

int large,small,quo,rem;
         cout << "\nEnter 2 numbers to divide: ";
	 cin >> large >> small;
	 quo = large / small;
	 rem = large % small;
	 cout << ""<< quo;
	 cout << " r "<< rem;

     return 0;
}

推荐答案

使用'/'和'%'运算符,你所做的基本上是正确的。作为替代方法,您可以使用运行时库的div和ldiv函数,它们返回结构中的商和余数。在一些可能稍微快一些的系统上,因为余数通常是除法的副产品。
What you are doing is basically correct, using the '/' and '%' operators. As an alternative you can use the div and ldiv functions of the runtime library, which return the quotient and remainder in a structure. On some systems that might be slightly faster, because the remainder is usually a by-product of the division.


如果 large 是小于,交换它们:

If the large is smaller than small, swap them:
if(bigger < smaller)
{
   int tmp = bigger;
   bigger = smaller;
   smaller = tmp;
}



这是您更正的程序:


Here is your corrected program:

#include <iostream>

using namespace std;

int main()
{ 
	int bigger, smaller;

	cout << "Enter a number:" << endl;
	cin >> bigger;

	cout << "Enter another number:" << endl;
	cin >> smaller;

	if(bigger < smaller)
	{
		int tmp = bigger;
		bigger = smaller;
		smaller = tmp;
	}

	int q = bigger / smaller;
	int r = bigger % smaller;

	cout << "Result: " << q << endl;

        if(r > 0)
	   cout << "Remainder: " << r << endl;

	return 0;
}
</iostream>


这篇关于C ++,将较大的数字除以较小的数字,并用商和余数表示答案。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆