【发布时间】:2015-06-01 10:18:55
【问题描述】:
希望我实现以下功能:
void calc ( double* a, double* b, int r, int c, double (*f) (double) )
参数a、r、c和f是输入,b是输出。 “a”和“b”是具有“r”行和“c”行的二维矩阵 列。 “f”是一个函数指针,可以指向以下类型的任何函数:
double function‐name ( double x ) {
…
}
函数calc将矩阵a中的每个元素,即aij,转换为矩阵b中的bij=f(aij)。
我实现calc函数如下,放到程序中测试一下:
#include <stdlib.h>
#include <iostream>
using namespace std;
double f1(double x){
return x * 1.7;
}
void calc (double* a, double* b, int r, int c, double (*f) (double))
{
double input;
double output;
for(int i=0; i<r*c; i++)
{
input = a[i];
output = (*f)(input);
b[i] = output;
}
}
int main()
{
// Input array:
int r=3;
int c=4;
double* a = new double[r*c];
double* b = new double[r*c];
// Fill "a" with test data
//...
for (int i=0; i<r*c; i++)
{
a[i] = i;
}
// Transform a to b
calc(a, b, r, c, f1);
// Print to test if the results are OK
//...
for (int i=0; i<r*c; i++)
{
b[i] = i;
}
return 0;
}
问题是,我无法编译它。这是我点击编译并执行按钮时DevC++的输出:
怎么了?
感谢您提出任何意见,以提高实施效率。
【问题讨论】:
-
\240是 iso8859-1 编码中的不间断空格,所以神秘的是那些非常特殊的字符是如何进入那里的。代码是用 Word 还是什么写的? -
@Wintermute hehe 我实际上仔细检查了 OP 与 person I met 16m ago 不一样 :)
-
代码对我来说编译得很好(g++ -o test.exe test.cpp),没有任何改动。你在 10 号线附近检查了吗?
-
你永远不会清理你分配的内存(提示:查看
std::vector以替换那些裸指针)。除此之外它看起来还不错。 @sehe 呵呵。就在几天前,我看到了另一个带有完全相同 Unicode 引号的问题。这让我感到疑惑。我的意思是,在任何像样的 IDE 中都很难偶然获得这些字符。 -
从 Adobe Acrobat 和 Adobe Reader 复制和粘贴也会导致该错误。 Sublime Text 可能有助于消除这些不需要的字符。
标签: c++ arrays function pointers matrix