如何解决为什么这个动态分配的实例不成功?
我正在尝试创建一个程序,该程序将 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
;所有整数算术。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。