如何获取数组第一个元素的镜像?
How do I get the mirror of the first element of an array?
我需要将数字输入一个数组,获取第一个数字,镜像它,然后查看该数组中的任何其他数字是否与镜像相同。
示例: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;
}
您的代码中存在两个主要问题。首先,您试图在 知道用户的输入值 n
之前分配 v
数组 ;这可以通过将 v
的 declaration/allocation 移动到 之后 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;
}
为什么不用整数交换字节,为什么不使用 itoa() 将每个数字转换为 C 字符串,然后使用 strrev() 反转字符串?
然后您可以将字符串与 strcmp() 进行比较。更少的代码,也更容易理解,更不容易出错。
我需要将数字输入一个数组,获取第一个数字,镜像它,然后查看该数组中的任何其他数字是否与镜像相同。
示例: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;
}
您的代码中存在两个主要问题。首先,您试图在 知道用户的输入值 n
之前分配 v
数组 ;这可以通过将 v
的 declaration/allocation 移动到 之后 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;
}
为什么不用整数交换字节,为什么不使用 itoa() 将每个数字转换为 C 字符串,然后使用 strrev() 反转字符串? 然后您可以将字符串与 strcmp() 进行比较。更少的代码,也更容易理解,更不容易出错。