首页 > 解决方案 > 如何处理负数:在 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", &dividend, &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;
}

标签: c

解决方案


顺便问一下,我的代码好不好?

嗯,还有改进的余地...

首先 -不要将不必要的变量传递给您的函数!

应除以的函数x应将yand作为参数。函数内部需要的任何变量都应在函数内部定义。xy

因此,第一步是将您的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;
}

推荐阅读