如何在C++中合并数组元素? 我想制作一个C++程序,它合并数组的元素,例如,我们有三个元素,它们是2到5,我们想合并它们,使一个数字为257
最简单的方法是使用基于范围的语句。比如说如何在C++中合并数组元素? 我想制作一个C++程序,它合并数组的元素,例如,我们有三个元素,它们是2到5,我们想合并它们,使一个数字为257 ,c++,C++,最简单的方法是使用基于范围的语句。比如说 #include <iostream> #include <cmath> int main() { const int N = 3; // the size of the array int a[N] = {2,5,7}; // define the number that will hold our final "merged" number int nbr = 0; // loop
#include <iostream>
#include <cmath>
int main()
{
const int N = 3; // the size of the array
int a[N] = {2,5,7};
// define the number that will hold our final "merged" number
int nbr = 0;
// loop through the array and multiply each number by the correct
// power of ten and add it to the merged number
for(int i=N-1;i>=0;--i){
nbr += a[i] * pow(10, N-1-i);
}
// print the number
std::cout << nbr << std::endl;
return 0;
}
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
这是演示程序
#include <iostream>
int main()
{
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
std::cout << "x = " << x << std::endl;
return 0;
}
同样可以使用在头文件中声明的标准算法std::accumulate来完成
考虑到数组必须具有可接受的值,如数字,并且生成的数字不会溢出给定类型累加器的可接受值范围。最有效的解决方案:
#include <iostream>
using namespace std;
int main()
{
const int N = 3;
int a[N] = {2,5,7};
int num = 0;
for(int i=0;i<N;i++)
num = num * 10 + a[i];
cout << num << endl;
return 0;
}
步骤:
数值->0
数值->2
数值->25
数值->257
对于这样一个广泛的问题,您至少应该添加一些解释,说明您的代码实际上做了什么。仅代码的答案在这里不适用。我添加了一些注释,现在更好了?这是一个有效的解决方案,因为结果数不大于int最大大小,这应该被提及。IDN我不只是发布或多或少的代码吗?数组的声明。但是,不是算法。你的算法没有这一个有效。你当然是指那里。那是怎么合并的?这是对数值的完全重新解释。
#include <iostream>
using namespace std;
int main()
{
const int N = 3;
int a[N] = {2,5,7};
int num = 0;
for(int i=0;i<N;i++)
num = num * 10 + a[i];
cout << num << endl;
return 0;
}