2

初投稿!これは "Advanced C & C++" の 2 学期なので、どんな助けも大歓迎です。私はすでに、この大量の論理的に不適切なコードで何を行っているか (または行っていないか) を理解するのに役立つように、stackoverflow と他のいくつかのリソースを精査しました。

このプログラムの目的は、ユーザーが指定した「数値」が回文であるかどうかを認識することです。シンプルですね。うーん...まあ、これは私が立ち往生しているものです:

#include <iostream>

using std::cout;
using std::cin;

#include <string>

using std::string;

#include <cstdlib>

int main()
{

//variable declarations
string buffer;

//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);

//looooop
while(buffer != "Q" && buffer !="q")
{
  int userNum, length, sum = 0, temp;
  userNum = atoi(buffer.c_str());
  for(temp = userNum; userNum !=0; userNum=userNum/10)
  {
    length = userNum % 10;
    sum = sum*10+length;
  }
  if(temp==sum)
    cout << temp << " is a palindrome!!\n\n";
  else
    cout << buffer << " is NOT a palindrome!\n\n";

  cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
  getline(cin, buffer);
}
}

「010」または「400」を入力した場合に問題が発生します。この場合、「400」は本質的に「00400」であり、どちらも回文と見なす必要があります。

4

2 に答える 2

0

より良いアプローチは、以下のように、指定された数値の末尾のゼロを取得することです。

int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;

または次のような整数の方法:

int noOfTrailingZeros = str.length;
while(num%10==0)
{
    noOfTrailingZeros++;
    num/=10;
}

ここで、入力文字列が数字の前にあるゼロの数と同じかどうかを確認します。

int counterZeros = 0;
while(str[counterZeros++]=='0');

これらの 2 つの数値を確認し、末尾のゼロが先頭のゼロよりも多い場合は、先頭にその数を追加し、その文字列を回文関数に渡します。

于 2013-09-29T06:24:52.800 に答える
0

まず第一に、回文を認識するために、あなたはする必要はありませんatoi. 最初から途中まで渡して

buffer[i] == buffer[length - i]

次に、 を使用しatoiて、それが数値であることを確認します。これで完了です。

もう 1 つの方法は、文字列を反転して比較することです。

string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}
于 2013-09-29T05:19:49.463 に答える