我需要将数字输入到一个数组中,获取第一个数字,对其进行镜像,然后查看该数组中的其他数字是否与镜像相同。
示例:4 个号码,123 321 111 和 200; 123 的镜像是 321,所以它应该告诉我"is",因为数组中还有 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
数组在您知道用户的输入值 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;
}
关于c++ - 如何获取数组第一个元素的镜像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65581825/