2016-01-20 58 views
0

写了下面的代码,但只能当第一个数字是对称的:计数多少次输入的号码,直到第一对称数字输入

对称性是这样的数字:4554(从两端阅读是一样的号码)

我的问题是为什么突破只适用于第一个号码?它发生在我运行它时。

#include <iostream> 

using namespace std; 

int main() 
{ 
    int n=0, z=0, r=0, x=0, m; 
    for (;;) { 
     cout << "Enter number: "; 
     cin >> x; 
     m = x; 

     while(x!=0) { 
      r = x % 10; 
      z = z * 10 + r; 
      x = x/10; 
     } 
     if(m==z) 
      break; 
     else 
      n++; 
    } 
    cout << n; 
    return 0; 
} 
+1

干得好,代码不错.....其实你的问题是什么? – jpo38

+0

知道这个问题会很酷。 – SergeyA

回答

2

Move int z = 0,r = 0;内部for循环。

+2

不需要'r'。 – SergeyA

+0

哦对,z每次需要为0,谢谢! –

0

为什么不使用此代码来知道数字是否是对称的?

#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int x; 
    for (;;) { 
     cout << "Enter number: "; 
     cin >> x; 
     m = x; 

     std::stringstream str; 
     str << x; 

     std::string number = str.str(); 
     if (number == std::string(number.rbegin(), number.rend()) 
      break; 
     else 
      n++; 
    } 
    cout << n; 
    return 0; 
} 

简单,导致了同样的结果,是肯定更容易出错;-)

+0

该死的看起来很复杂xD。我没有学过字符串或任何东西.. –

+0

这很可能是一个任务。 – SergeyA

+0

@SergeyA:当然......但这并不意味着你必须操纵数字(除非OP发布了赋值约束....)。它看起来更优雅,而且更容易理解代码的作用.....老师肯定会对答案感到惊讶,但可以接受它;-) – jpo38

0

这本来是更容易理由,如果你这样写的:

#include <iostream> 

bool isPalindrome(int x) 
{ 
    int y = x; 
    int z; 
    while (x) { 
     z = z * 10 + x % 10; 
     x /= 10; 
    } 
    return y == z; 
} 

int main() 
{ 
    int n = 0; 
    int x; 
    for (;;) { 
     std::cout << "Enter number: "; 
     std::cin >> x; 
     if (isPalindrome(x)) 
      break; 
     else 
      ++n; 
    } 
    std::out << "Number of non-palindromes: " << n << std::endl; 

    return 0; 
} 

有意义的名字功能总是有帮助!

相关问题