C ++程序计算分段函数(涉及指针)

时间:2020-07-20 08:58:34

标签: c++ function pointers

嗨,我目前的代码有问题。我正在设计一个涉及指针的程序,其中提示用户输入最小值,然后将计算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 个答案:

答案 0 :(得分:1)

根据给出的代码和所提供的信息,我尝试尽可能地对其进行调试。

我遇到的错误:

1。。您已将函数library(tidyr) example.tidy <- pivot_longer(example.data, cols = c(str_which(colnames(example.data), "Abundance: [^F]"), str_which(colnames(example.data), "Found in Sample Group")), names_to = c(".value", "Sample", "Polymer", "Fraction"), names_pattern = "(.*): (.*), (.*), (.*)") 声明为void piecewise(double[], int);,但在void中返回了int

2。。您需要在函数int piecewise(fx, min);中提供列的大小,因为我遇到了 错误:多维数组必须对所有维都具有边界首先

3。。您需要正确提供指针void piecewise(double[], int);,而不只是ptr = &fx[i][0];,并且还像ptr = &fx[i];一样正确地取消引用。

4。。您需要从函数cout << text1 << *ptr;中的i=0开始循环,而不要从void piecewise(double fx[][2], int min)

开始循环

修改后的代码:

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