首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我的函数找出两个其他数字输入的数字的总和,在C中不起作用?

我的函数找出两个其他数字输入的数字的总和,在C中不起作用?
EN

Stack Overflow用户
提问于 2019-06-24 08:52:31
回答 1查看 44关注 0票数 -1

正如标题所说,我正在尝试找出输入到函数中的数字中每隔一位数字的两个数字的总和。第一个数字将是倒数第二位。例如,输入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;
}
EN

回答 1

Stack Overflow用户

发布于 2019-06-24 09:03:05

你有两个bug。

首先,您希望每个循环只执行一次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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56728736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档