繁体   English   中英

我的用于查找输入的每个其他数字的两倍的数字总和的功能在 C 中不起作用?

[英]My function to find the sum of the digits of twice of every other number entered is not working in C?

正如标题所说,我试图在输入到函数中的数字中找到每隔一个数字两次的数字总和。 第一个数字将是倒数第二个数字。 例如,输入 58423 应该返回 2*2 (4), 8*2 (16-> 1+6 = 7) -- >4+7 = 11。我的根本不是那样工作,似乎返回随机数字。 功能如下。

我正在使用这样一个事实,即 n % 10 将为您提供 n 的最右侧数字,而 (n / 10) % 10 将为您提供 n 的下一个最右侧数字,依此类推,其中 n 是输入的数字。

int everyOther(long num) //(n / 10) % 10 will get you the next rightmost 
digit
{
    int incrementer = 1;
    int total = 0;
    long shifter = 1;
    int a = 0;
    while(true)
    {
        shifter = shifter *100;
        if(num/shifter == 0) 
        {
            break; // will have reached the end of the number if this is 
//true
        }
        a = 2* ((num / shifter) % 10); // every other digit right to left 
//starting from the second to last, multiplied by two
        total = total + (a/10 + a%10); //sum of the above product's 
//digits
        incrementer++;

    }
    return total;
}

你有两个错误。

首先,你只想做shifter = 100 * shifter; 每个循环一次。 在每次迭代中,您希望shifter是前一次迭代的 100 倍。 所以只需乘以 100 一次。 你可以摆脱incrementer 这是多余的。

其次,您的示例显示添加 16 的数字以获得 7。但出于某种原因,您注释掉了代码以执行此操作。

int everyOther (long num)
{
    int shifter = 1; // dividing by 10 gets us the hundreds digit
    int total = 0;
    int a = 0;
    while (num/shifter > 0)
    {

        shifter *= 100; // move two digits over
        if(num/shifter == 0) 
          {
              break;  
          }
        a = 2 * ((num / shifter) % 10);
        total += (a/10 + a%10);

    }
    return total;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM