c - 如何处理负数:在 C 中不使用“/”、“%”和“*”运算符获取商和余数
问题描述
该程序适用于处理正整数,但不适用于负整数。我该如何解决这个问题?谢谢!
顺便问一下,我的代码好不好?在不使用“/”、“%”和“*”运算符的情况下,有没有更好的方法来获得商和余数?
#include <stdio.h>
int divide(int x, int y, int quotient);
int getRem(int x, int y, int quotient, int product, int count,
int remainder);
int main()
{
int dividend, divisor, quotient = 0, product = 0;
int remainder, count = 0;
scanf("%d %d", ÷nd, &divisor);
printf("\nQuotient: %d", divide(dividend, divisor, quotient));
quotient = divide(dividend, divisor, quotient);
printf("\nRemainder: %d", getRem(dividend, divisor, quotient, product, count, remainder));
}
int divide(int x, int y, int quotient)
{
while (x > 0)
{
x -= y;
quotient++;
}
if (x != 0)
return quotient - 1;
else
return quotient;
}
int getRem(int x, int y, int quotient, int product, int count, int remainder)
{
while (count != y)
{
product += quotient;
count++;
remainder = x - product;
}
return remainder;
}
解决方案
顺便问一下,我的代码好不好?
嗯,还有改进的余地...
首先 -不要将不必要的变量传递给您的函数!
应除以的函数x
仅应将y
and作为参数。函数内部需要的任何变量都应在函数内部定义。x
y
因此,第一步是将您的divide
功能更改为:
int divide(int x, int y)
{
int quotient = 0; // use a local variable
while (x > 0)
{
x -= y;
quotient++;
}
if (x != 0)
return quotient - 1;
else
return quotient;
}
另一个(次要)问题是两个返回语句。用一个简单的改变while
语句就可以避免。
int divide(int x, int y)
{
int quotient = 0; // use a local variable
while (x >= y) // notice this change
{
x -= y;
quotient++;
}
return quotient;
}
另请注意,调用 likedivide(42, 0);
将导致无限循环。所以也许你应该检查y
是否为零。
该算法可以改进 - 特别是对于大量数字 - 但我想你想要一个简单的方法,所以我坚持你的基本算法。
...但不是负整数。我该如何解决这个问题?
一个简单的方法是在进入循环之前转换任何负输入并维护一个计数器来记住负数的数量。就像是:
int divide(int x, int y)
{
int quotient = 0;
int negative = 0;
if (x < 0)
{
x = -x; // Make x positive
++negative;
}
if (y < 0)
{
y = -y; // Make y positive
++negative;
}
while (x >= y) // Both x and y are positive here
{
x -= y;
quotient++;
}
return (negative == 1) ? -quotient : quotient;
}
int main(void)
{
printf("%d\n", divide( 5, 2));
printf("%d\n", divide( 5,-2));
printf("%d\n", divide(-5, 2));
printf("%d\n", divide(-5,-2));
printf("%d\n", divide( 6, 2));
printf("%d\n", divide( 6,-2));
printf("%d\n", divide(-6, 2));
printf("%d\n", divide(-6,-2));
return 0;
}
输出:
2
-2
-2
2
3
-3
-3
3
您可以对函数应用相同类型的更改getRem
,我将把这部分留给您作为练习......
但是,请注意,您当前的函数使用quotient
没有任何好处。该函数(仅处理正数)可以简单地是:
int getRem(int x, int y) // requires x >= 0 and y > 0
{
while (x >= y)
{
x -= y;
}
return x;
}
推荐阅读
- firefox - 无法使用 tornado 6.1.0.0、python 3.73 在 Firefox 90.02 或 78.13.0esr 中设置安全 cookie。好的铬,边缘等
- c++ - 为什么我的代码会在 x86-64 上导致三重错误?
- ios - 如何在 AVCapture 中添加对焦曝光和闪电
- vue.js - 未找到 notifilix-react 包
- typescript - 如何防止 T 或 Promise 的类型扩大
? - android-recyclerview - 使用 Horizontal RecyclerView 使 View 滚动
- ruby-on-rails - 为什么我在上传多张图片时会收到 InvalidSignature 错误?
- python - 如何在具有基本事实的情况下仅针对数据框找到 True Postive?
- python-3.x - 编写一个程序,计算 PYTHON3 中输入的 0 和 1 序列中出现“11”的次数
- html - 选择div中的第一个元素