You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决数字循环右移匹配问题及函数返回值警告?

解决循环右移数字匹配的函数警告与逻辑问题

一、先搞定返回值警告的直接原因

你的circular函数触发警告的核心原因:当while循环的初始条件ca != b && contor <= nrCif(a)不成立时(比如a一开始就等于b),函数没有任何return语句,编译器认为存在未返回值的控制路径。

二、彻底修复函数的逻辑错误

除了返回值问题,你原代码的循环右移逻辑也错得离谱,下面是一步步的修复方案:

1. 补全nrCif的边界处理

原函数遇到0会返回0,这会导致后续计算出问题,加个判断:

int nrCif(int a)
{
    if (a == 0) return 1; // 0本身是1位数
    int nr = 0;
    while(a != 0){
        nr ++;
        a /= 10;
    }
    return nr;
}

2. 换掉pow,避免精度坑

pow返回的是double类型,转int时容易出现精度丢失(比如pow(10,3)可能算出999.999999,强转int就变成999),自己写个整数版的10次幂函数:

int power10(int n) {
    int res = 1;
    for (int i = 0; i < n; i++) {
        res *= 10;
    }
    return res;
}

3. 重新实现循环右移的正确逻辑

循环右移的正确操作是把最后一位移到最前面,比如1234右移一次变4123,再移一次变3412。你原代码的右移逻辑完全不对,直接重构circular函数:

4. 修正后的circular函数

int circular(int a, int b)
{
    if (a == b) return 0; // 一开始就相等,不用动
    int digits = nrCif(a);
    int temp = a;
    int count = 0;
    int tenPower = power10(digits - 1); // 比如4位数就是1000

    // 最多循环digits次,因为循环digits次会回到原数
    while (count < digits) {
        // 执行一次循环右移
        int lastDigit = temp % 10;
        temp = lastDigit * tenPower + temp / 10;
        count++;
        if (temp == b) {
            return count;
        }
    }
    // 循环完所有可能都没匹配上,返回-1
    return -1;
}

5. 删掉没用的inversa函数

修正逻辑后,反转数字的函数完全用不上,直接删掉就行。

三、完整修复后的代码

#include <iostream>

using namespace std;

int nrCif(int a)
{
    if (a == 0) return 1;
    int nr = 0;
    while(a != 0){
        nr ++;
        a /= 10;
    }
    return nr;
}

int power10(int n) {
    int res = 1;
    for (int i = 0; i < n; i++) {
        res *= 10;
    }
    return res;
}

int circular(int a, int b)
{
    if (a == b) return 0;
    int digits = nrCif(a);
    int temp = a;
    int count = 0;
    int tenPower = power10(digits - 1);

    while (count < digits) {
        int lastDigit = temp % 10;
        temp = lastDigit * tenPower + temp / 10;
        count++;
        if (temp == b) {
            return count;
        }
    }
    return -1;
}

int main()
{
    int a, b;
    cin >> a >> b;
    cout << circular(a, b);
    return 0;
}

四、关键问题说明

  • 你原函数的while循环里每次循环都直接return,导致循环只跑一次就退出,根本没法多次右移判断
  • 用整数运算替代pow彻底解决精度问题
  • 补充了0的边界处理,避免位数计算错误
  • 循环次数限制为数字位数,因为循环n次后数字会回到原始状态,没必要继续循环

内容的提问来源于stack exchange,提问作者beni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:28:10