2014-09-06 416 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

相關問題