问题描述
我正在尝试创建一个程序,该程序将 10 的索引号幂(索引 0 为 1,索引 1 为 10,索引 2 为 100,等等)。当我运行这个程序时,它不输出任何东西。有什么问题?
#include<iostream>
#include<cmath>
using namespace std;
int* powersOfTwo(int n);
int* powersOfTwo(int n)
{
int i,x=10;
n=3;
int *arr = new int(n);
for (i=0; i<=n; i++) {
arr[i]=pow(x,i);
cout<<arr[i]<<endl;
}
return 0;
}
int main() {
powersOfTwo;
return 0;
}
解决方法
您可能希望在不调用 pow
的情况下循环执行操作:
void powerOfTwo(std::vector<int>& powers,int quantity)
{
int power = 1;
powers.push_back(power);
for (int i = 0; i < quantity; ++i)
{
power = power * 10;
powers.push_back(power);
}
}
int main()
{
std::vector<int> database;
powersOfTwo(database,10);
for (int i = 0; i < 10; ++i)
{
std::cout << " " << database[i];
}
std::cout << "\n";
return 0;
}
注意事项:
- 向量是通过引用传递的,因此可以对其进行修改。
- 没有强制动态内存分配;没有泄漏。
- 矢量将根据需要扩展。
- 10 的幂将通过幂或幂的数学定义来计算。
- 没有调用
power
;所有整数算术。