用c++程序计算求解分段函数(涉及指针)



嗨,我的代码目前有问题。我正在设计一个涉及指针的程序,提示用户输入最小值,然后计算f(x(,结果将存储在数组中。

我的代码中有一些错误,但我不太确定如何解决。

我希望有人能帮我做这件事,谢谢你。

#include <iostream>
using namespace std;
void piecewise(double[], int);
int main() {
double fx[10][2] = {0};
double *ptr;
string text1 = "For x = ", text2 = ", f(x) = ";
int min;
cout << "Enter min integer value for x: ";
cin >> min;
int piecewise(fx, min);
for (int i = 0; i < 10; i++) // ptr points to row i column 0
{
ptr = &fx[i];
cout << text1 << ptr;
cout << text2 << fx[i][1] << endl;
}
return 0;
}
void piecewise(double fx[][2], int min) {
int x = min;
for (int i = 1; i < 10; i++) {
fx[i][0] = x;
if (x < 2)
fx[i][1] = x * x;
else if (x == 2)
fx[i][1] = 6;
else
fx[i][1] = 10 - x;
x++;
}
}

根据给出的代码和提供的信息,我尽可能多地调试它。

我遇到的错误:

1。您已将函数void piecewise(double[], int);声明为void,但在int piecewise(fx, min);中返回了int

2.当我遇到错误时,您需要在函数void piecewise(double[], int);中提供列的大小:多维数组必须对除第一个之外的所有维度都有边界。

3。您需要正确地提供指针ptr = &fx[i][0];,而不仅仅是ptr = &fx[i];,并像cout << text1 << *ptr;一样正确地取消引用它。

4.您需要从函数void piecewise(double fx[][2], int min)中的i=0开始循环,而不是从i=1.开始循环

修改后的代码:

#include <iostream>
using namespace std;
void piecewise(double[][2], int);
int main() {
double fx[10][2] = {0};
double *ptr;

string text1 = "For x = ", text2 = ", f(x) = ";
int min;
cout << "Enter min integer value for x: ";
cin >> min;
piecewise(fx, min);
for (int i = 0; i < 10; i++) // ptr points to row i column 0
{
ptr = &fx[i][0];
cout << text1 << *ptr;
cout << text2 << fx[i][1] << endl;
}
return 0;
}
void piecewise(double fx[][2], int min) {
int x = min;
for (int i = 0; i < 10; i++) {
fx[i][0] = x;
if (x < 2)
fx[i][1] = x * x;
else if (x == 2)
fx[i][1] = 6;
else
fx[i][1] = 10 - x;
x++;
}
}

输入:

Enter min integer value for x: 4

输出:

For x = 4, f(x) = 6                                                                                                   
For x = 5, f(x) = 5                                                                                                   
For x = 6, f(x) = 4
For x = 7, f(x) = 3                                                                                                   
For x = 8, f(x) = 2                                                                                                   
For x = 9, f(x) = 1                                                                                                   
For x = 10, f(x) = 0   
For x = 11, f(x) = -1
For x = 12, f(x) = -2
For x = 13, f(x) = -3

最新更新