【发布时间】:2021-03-04 15:40:11
【问题描述】:
我正在尝试计算数字数组中数字的算术平均值。
我正在尝试使用动态内存分配和指针。
我想不出更快或更好的方法。
void media_cifrelor(int *p, int &x)
{
int *w = new int[x];
for (int i = 0; i < x; i++)
{
int k = 0;
while (*(p + i) != 0)
{
k++;
*(w + i) += *(p + i) % 10;
*(p + i) /= 10;
}
*(w + i) /= k;
cout << *(w + i) << " ";
cout << endl;
}
cout << endl;
}
//p1.txt
// 7
// 12 231 9012 34 8123 22 507
int main()
{
ifstream fisier("p1.txt");
int n, *v;
v = citire(fisier, n); // int *citire(ifstream &fisier, int &x)
cout << "n= " << n << endl;
// for (int i = 0; i < n; i++)
// {
// cout << *(v + i) << " ";
// }
cout << endl;
media_cifrelor(v, n);
return 0;
}
cout << *(w + i) << " "; 每次运行都会返回随机负值,我不明白错误在哪里。
从文件中读取函数:
int *citire(ifstream &fisier, int &x)
{
if (fisier.is_open())
{
int *p;
fisier >> x;
// cout << "x= " << x << endl;
p = new int[x];
for (int i = 0; i < x; i++)
{
fisier >> *(p + i);
// cout << *(p + i) << " ";
}
cout << endl;
return p;
}
else
{
cout << "Could not open file" << endl;
return 0;
}
}
【问题讨论】:
标签: c++