c++ - 一个程序来判断一个单词是否是回文
问题描述
编写一些算法来找出给定的单词是否是回文。但是counter
当我调试时,我的一个变量 ( ) 似乎没有更新,我无法弄清楚它有什么问题。我可能是错的......因为我不想盲目地在线复制一些代码,所以需要任何帮助。下面是代码:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
//take input
string input;
cout << "Enter your word: ";
cin >> input;
//initialize arrays and variables
int counter = 0, k = 0;
int char_length = input.length();
char characters[char_length];
strcpy(characters, input.c_str());//copy the string into char array
//index of character at the midpoint of the character array
int middle = (char_length-1)/2;
int booleans[middle]; //to keep 1's and 0's
//check the characters
int m = 0, n = char_length-1;
while(m < middle && n > middle){
if(characters[m] == characters[n]){
booleans[k] = 1;
} else {
booleans[k] = 0;
}
k++;
m++;
n--;
}
//count number of 1's (true for being equal) in the booleans array
for(int i = 0; i < sizeof(booleans)/sizeof(booleans[0])-1; i++){
counter += booleans[i];
}
//compare 1's with size of array
if(counter == middle){
cout << input << " is a Palindrome!" << endl;
} else {
cout << input << " is not a Palindrome!" << endl;
}
return 0;
}
解决方案
兄弟,您似乎很难理解您的问题是什么以及您正在输入什么代码。我不是很有经验,但根据我的说法,回文是一个非常简单易行的程序,我会把它写成:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[20], str2[20];
int i, j, len = 0, flag = 0;
cout << "Enter the string : ";
gets(str1);
len = strlen(str1) - 1;
for (i = len, j = 0; i >= 0 ; i--, j++)
str2[j] = str1[i];
if (strcmp(str1, str2))
flag = 1;
if (flag == 1)
cout << str1 << " is not a palindrome";
else
cout << str1 << " is a palindrome";
return 0;
}
它适用于您可以尝试的所有情况。
推荐阅读
- javascript - 在导入 FormlyModule 并注册默认类型的动态模块中传递自定义类型
- python - 使用 Flask 和 Pytest 对 Redis 进行单元测试
- mongodb - Default timestamp is not working with Mongoose
- intellij-idea - 如何使用 IntelliJ IDEA 使用 PlantUML 图保存从 Markdown 呈现的 HTML 文件?
- c++ - 更新线程本地值(并发 C++)
- java - ScheduledThreadPoolExecutor 可能存在内存泄漏
- r - 如何根据数组中的不同列值对行进行排序,但在 R 中的矩阵中单独工作
- ios - (CoreBluetooth)代码出于某种原因将无法继续
- php - 在 PHP 中更新 CSV 文件的内容
- go - 无法连接到弹性搜索:找不到活动连接:没有可用的弹性搜索节点