21xrx.com
2025-03-27 04:19:13 Thursday
文章检索 我的文章 写文章
C++编程:统计5位数中含有几个4并且是回文数
2023-06-26 22:38:08 深夜i     15     0
C++ 编程 统计 5位数 4 回文数

回文数指的是正着读和倒着读都相同的数,例如121、1221等等。在这篇文章中,我们将会学习如何使用C++编程语言来统计5位数中含有几个4并且是回文数。下面就是具体的步骤:

首先,我们需要遍历所有的5位数,并且判断这些数字是否含有4。我们可以使用for循环语句来实现:

int count = 0;
for (int i = 10000; i <= 99999; i++) {
  std::string number = std::to_string(i);
  if (number.find('4') != std::string::npos) {
    count++;
  }
}

在这个循环中,我们使用了一个标志变量count来记录含有4的数字的个数。使用std::to_string()函数将数字转换成字符串,使用std::string::find()函数来查找字符串中是否含有4。如果该函数返回的位置不为std::string::npos,则表示该字符串中含有4,此时count变量加1。

接下来,我们需要判断这些含有4的数字是否是回文数。同样地,我们可以使用for循环语句来实现:

for (int i = 10000; i <= 99999; i++) {
  std::string number = std::to_string(i);
  if (number.find('4') != std::string::npos) {
    bool isPalindrome = true;
    for (int j = 0; j < number.length() / 2; j++) {
      if (number[j] != number[number.length() - j - 1])
        isPalindrome = false;
        break;
      
    }
    if (isPalindrome) {
      count++;
    }
  }
}

在这个循环中,我们增加了一个bool类型的变量isPalindrome,用来记录该数字是否是回文数。使用一个内层的for循环来比对数字的前一半和后一半是否相同,如果存在不相同的则表示该数字不是回文数,此时isPalindrome变量设为false。如果该数字是回文数,则isPalindrome变量为true,此时count变量加1。

最后,我们可以在循环结束之后输出含有4且为回文数的数字的个数:

std::cout << "含有4且为回文数的数字的个数为:" << count << std::endl;

完整的程序如下所示:

#include <iostream>
#include <string>
int main()
{
  int count = 0;
  for (int i = 10000; i <= 99999; i++) {
    std::string number = std::to_string(i);
    if (number.find('4') != std::string::npos) {
      bool isPalindrome = true;
      for (int j = 0; j < number.length() / 2; j++) {
        if (number[j] != number[number.length() - j - 1])
          isPalindrome = false;
          break;
        
      }
      if (isPalindrome) {
        count++;
      }
    }
  }
  std::cout << "含有4且为回文数的数字的个数为:" << count << std::endl;
  return 0;
}

这就是如何使用C++编程语言来统计5位数中含有几个4并且是回文数的方法。希望本文对你有所帮助。

  
  

评论区

    相似文章
请求出错了