首页 > 解决方案 > 如何获取数组第一个元素的镜像?

问题描述

我需要将数字输入一个数组,获取第一个数字,将其镜像,然后查看所述数组中的任何其他数字是否与镜像相同。

示例:4 个号码,123 321 111 和 200;123 的镜像是 321,所以它应该告诉我“是”,因为数组中还有 1 个元素与镜像相同。

#include <iostream>
    
using namespace std;
    
int main()
{
    int n = 0, mirror, cnt = 0;
    int* v = new int[n];
    
    cout << "How many elements?\n";
    cin >> n;
    
    for(int i=0; i<n; i++)
        cin >> v[i];
    
    while(v[0] != 0){
        mirror = mirror * 10 + v[0] % 10;
        v[0] /= 10;
    }
    cout << mirror;
    for(int i=0; i<n; i++)
        if(v[i] == mirror && v[i] != v[0])
            cnt++;
    if(cnt >=1)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

标签: c++arraysmirror

解决方案


您的代码中有两个主要问题。首先,您试图在知道用户的输入值之前v分配数组;这可以通过在该行之后移动 to 的声明/分配来解决。nvcin >> n;

其次,你永远不会给mirror变量一个初始(零)值,所以它可以从任何东西开始,然后你将数字的值添加到你的while循环中。

这是您的代码的固定版本,在更改的行上有注释:

#include <iostream>

using namespace std;

int main()
{
    int n = 0, mirror = 0, cnt = 0; // MUST initialize "mirror"

    cout << "How many elements?\n";
    cin >> n;
    int* v = new int[n]; // CAN ONLY allocate the array AFTER we have input the value of "n"

    for (int i = 0; i < n; i++)
        cin >> v[i];

    while (v[0] != 0) {
        mirror = mirror * 10 + v[0] % 10;
        v[0] /= 10;
    }
    cout << mirror;
    for (int i = 0; i < n; i++)
        if (v[i] == mirror && v[i] != v[0])
            cnt++;
    if (cnt >= 1)
        cout << "Yes";
    else
        cout << "No";

    delete[] v; // For good coding style, don't forget to deallocate the array!
    return 0;
}

推荐阅读