【问题标题】:How to run a c program using loops to find the remainder of two numbers without using multiplication, division and modulo operators?如何在不使用乘法、除法和模运算符的情况下使用循环运行 c 程序来查找两个数字的余数?
【发布时间】:2021-11-18 07:51:55
【问题描述】:
#include <stdio.h>

int main()
{
    int num1, num2;

    printf ("Input value for num1: ");
    scanf ("%d", &num1);
    printf ("Input value for num2: ");
    scanf ("%d", &num2);   

    int prod =0, i;
    for(i = 1; i <= num1; i++){
        prod += num2;
    }

    int quo = 0 , rem = 0;
    for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
        if(rem < 0)             
            break;
        else
            quo++;
    }

    //The last part is that i need to find the remainder without  using multiplication, division and the modulo itself.

    printf ("The product of %d and %d is: %d\n", num1, num2, prod);
    printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);

    return 0;
}

【问题讨论】:

  • 而且,我真的不知道该怎么做。我希望有人能帮助我。
  • 您忘记告诉我们发布代码的问题
  • 余数为rem + num2
  • 提示:10 除以 3 为 3,其余为 1。10 - 3 = 7。7 - 3 = 4。4 - 3 = 1。现在 1 小于 3,1 是休息。
  • 注意if(rem &lt; 0) break; else是不必要的,它重复了循环条件rem &gt;= 0

标签: c loops


【解决方案1】:

对于正整数ab,仅用减法和加法计算a mod b 的最简单解决方案是从a 中减去b,直到结果小于a。但是,如果b 远小于a,则需要多次迭代。

一种在最坏情况下性能更好的方法如下:

#include <stdio.h>

unsigned rem(unsigned a, unsigned b)
{
    if(b == 0) return 0;  // Error
    while(a >= b)
    {
        unsigned s = b;
        do
        {
            a = a - s;
            s = s + s;
        } while(a >= s);
    }
    return a;
}

int main(void)
{
    unsigned example = rem(32453, 3);
    printf("%u\n", example);
}

这种方法是基于这样一个事实,即为了更接近结果,我们可以减去b的任意倍数,只要它小于a,所以在每次内部迭代中我们尝试减去两倍的倍数最后一次迭代,直到减法器变得太大,我们从b的单个倍数重新开始。

请注意,如果s = s + s; 溢出unsigned 范围,这将给出错误结果。因此,a 不应大于 unsigned 上限的一半。

【讨论】:

    【解决方案2】:

    如果您想要计算num1 % num2(即没有乘法/除法),您可以这样做:

    // Calculate num1 % num2
    
    unsigned rem(unsigned num1, unsigned num2)
    {
        if (num2 == 0) {.... error handling ....}
    
        while (num1 >= num2) num1 -= num2;
        return num1;
    }
    
    int main(void)
    {
        unsigned num1 = 42;
        unsigned num1 = 3;
        unsigned rem = rem(num1, num2);
        printf("%u", rem);
        return 0;
    }
    

    【讨论】:

    • 我将把这部分放在哪里?它一直说错误:“rem”重新声明为不同类型的符号 26 |无符号雷姆(无符号数1,无符号数2)| ^~~
    • @serra 你把函数放在main() 函数之前。下面我会做一个完整的例子。
    • @nielsen 非常感谢!我会等
    • @serra 看看我的回答(上面或下面,它似乎在移动:))
    • @serra 查看更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多