C ++删除数字的第一个和最后一个数字

时间:2014-09-06 00:49:45

标签: c++ loops counting modulus

我正在尝试编写一个程序来摆脱数字的第一个和最后一个数字。对于最后一位数字,以10为单位跳水可解决该问题。我需要找到一种方法来使用%来删除第一个数字,但似乎我的逻辑在某处,我的程序运行但它无法正常工作。看到逻辑中的任何错误?

#include <iostream>
using namespace std;

int main() {
    int x;
    int y;
    cout << "Enter a number to have the first and last didgets removed" << endl;
    cin >> x;

    x /= 10;
    y = x;
    int count = 0;

    while (y > 1)
    {
        y /= 10;
        count++;
    }

    int newNum = x %(10 ^ (count));

    cout << newNum << endl; 
    cin.ignore();
    cin.get();

    return 0;
}

4 个答案:

答案 0 :(得分:2)

有几个问题,但关键的问题可能是:

int newNum = x %(10 ^ (count));

^是按位xor不是是强力运营商。

相反,您可以尝试这样的事情:

int newNum;
if (y < 10)
    newNum = 0; // or what should it be?
else
{
    int denominator = 1;
    while (y >= 10)
    {
        y /= 10;
        denominator *= 10;
    }
    newNum = x % denominator;
}

P.S。算法越来越短,但我试图保留给定算法的逻辑。

答案 1 :(得分:2)

另一个类似的整数算术解决方案:

#include <iostream>
using namespace std;

int main() {
    int x;
    int y;
    cout << "Enter a number to have the first and last didgets removed" << endl;
    cin >> x;

    x /= 10;
    y = x;
    int count = 0;

    while (y > 9) {
        y /= 10;
        ++count;
    }
    for (int i = 0; i < count; i++) 
        y *= 10;
    x -= y;

    cout << x << endl; 
    cin.ignore();
    cin.get();

    return 0;
}

答案 2 :(得分:0)

#include <iostream>
using namespace std;

int main() {

    int n,a,b,c,d,e,f,g,h=0, bb, sum;
    cin>>n;
    d=n;
    b=n/10%10;
    while(n>99) {
        n=n/10;
        c=n/10;
        c=n%10;
        g=(n/10)/(n/10);
        h=h+g;
    }
    a=b;
    f=d-(a*10)+(c*10);
    while(d>99)
        d=d/10;
    switch(h)
    {
        case 2: bb=100; break;
        case 3: bb=1000; break;
        case 4: bb=10000; break;
        case 5: bb=100000; break;
        case 6: bb=1000000; break;
        case 7: bb=10000000; break;
        case 8: bb=100000000; break;
        case 9: bb=1000000000; break;
    }
    e=f-(f/bb)*bb;
    sum=((d/10)*10+(a))*bb+e;
    cout << sum << endl;
}

答案 3 :(得分:0)

我知道如何删除第一个数字 here 的答案。

#include <cmath>
#include <string>

void remove_first(int &num) {
    num %= static_cast<int>(pow(10, static_cast<size_t>(log10(num))));
}

本质上它是这样做的x % (10 ^ floor(log10(x)))

要删除最后一位数字,只需将数字除以 10,然后按照您最初的计划取出整个部分 (floor(x / 10))。

相关问题