c++ - 如何获取数组第一个元素的镜像?
问题描述
我需要将数字输入一个数组,获取第一个数字,将其镜像,然后查看所述数组中的任何其他数字是否与镜像相同。
示例: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;
}
解决方案
您的代码中有两个主要问题。首先,您试图在知道用户的输入值之前v
分配数组;这可以通过在该行之后移动 to 的声明/分配来解决。n
v
cin >> 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;
}
推荐阅读
- reverse-engineering - 关于 PLT/GOT 和静态链接的问题
- kotlin - 未解决的参考:颜色
- android - 在 Android 的 Spinner 中选择项目时如何从 ROOM 数据库中获取特定数据
- java - 对于 String 类型,方法 strip() 未定义
- ansible - Ansible 库存:使用主机变量定义组从属关系
- sql - 使用嵌套行(类型 STRUCT)对表 SQL 进行重复数据删除
- android - 错误:无法找到带有 Gradle 路径“:capacitor-cordova-android-plugins”的模块
- java - 如何从数组中的列表视图中获取值
- lmdb - 在特定情况下,LMDB 是否也可以并发写入?
- python - Python 3 Discord Bot 函数添加到自身