2014-09-06 449 views
2

我正在尝试编写一个程序来摆脱数字的第一个和最后一个数字。对于最后一位数字,通过10次解决这个问题。我需要找到一种方法来使用%来删除第一个数字,但是似乎我的逻辑已关闭,我的程序运行但它无法正常工作。查看逻辑中的任何错误?C++删除数字的第一个和最后一个数字

#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; 
} 

回答

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; 
} 

附:有更短更快的算法,但我试图保留给定的逻辑。

+0

非常感谢,我现在知道了。我必须改变的唯一代码是int newNum = pow(10,count); \t \t x%= newNum; \t \t cout << x << endl;感谢您的帮助。 – 2014-09-06 01:06:47

+0

@XerradAnon我不会去'pow'。如果由于四舍五入,你会得到'9999.99 ...'而不是'10000'。即使这在实践中没有发生,这种方法仍然是可疑的和冒险的。 – AlexD 2014-09-06 01:11:04

+0

@XerradAnon另外'while(y> 1)'看起来不正确。尝试使用以'1'开头的数字和其他数字进行测试。 – AlexD 2014-09-06 01:28:04

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; 
} 
+0

感谢您使用我的代码并修复了需要完成的工作,这使得理解逻辑变得容易很多,因为大部分工作都是我所做的,我可以轻松地遵循您的解决方案。 – 2014-09-06 01:36:21

+0

@XerradAnon不客气。 – JosEduSol 2014-09-06 01:37:03

相关问题