首页 > 解决方案 > 函数'c ++中数组元素的操作

问题描述

我可以在函数中(在参数中)操作数组的元素吗?

float f(i, u, v)
{
    if (i == 1) {
        return (u - v); //example of the returned value
    }
    if (i == 2) {
        return (u + v);
    }
}
int main()
{
    int i;
    float x[3],y1,y2,h;
    x[1]=1;//value of the first element of x[m]
    x[2]=1;
    h=0.01;
    for (i = 1; i <= 2; i++) {
        y1=h * f(i, x[1], x[2]);
        y2=h * f(i, x[1] + y1/2, x[2]+y1/2);
        y3=h* f(i,x[1] + y2/2, x[2]+y2/2);
        y4=h * f(i,x[1] + y3, x[2]+y3);
        x[1]=x[1] + (y1+ 2 * y2 + 2 * y3+2 * y4)/ 6;
        x[2]=x[2] + (y1+ 2 * y2 + 2 * y3+2 * y4)/ 6;
        cout<<x[1]<<endl;
        
    }
}

with: x[1]x[2] 是数组的元素x[m] 如何在参数中操作不同数组的元素?

标签: c++

解决方案


我建议你尝试编译你的代码,编译器会给你一些重要的提示,说明什么是错误的。是网上编译的代码。

为了使它编译,我将其更改

#include <iostream>

using namespace std;

float f(int i, float u, float v) {
    if (i == 1) {
        return (u - v); // example of the returned value
    }
    // if (i == 2) { // This if-statement is not needed
        return (u + v);
    // }
}

int main() {
    int i;
    float x[3] = {0, 1, 1}; // x[0] is unused...?
    float y1 = 0;
    float y2 = 0;
    float y3 = 0;
    float y4 = 0;
    const float h = 0.01;
    for (int i = 1; i <= 2; i++) {
        y1 = h * f(i, x[1], x[2]);
        y2 = h * f(i, x[1] + y1 / 2, x[2] + y1 / 2);
        y3 = h * f(i, x[1] + y2 / 2, x[2] + y2 / 2);
        y4 = h * f(i, x[1] + y3, x[2] + y3);
        x[1] = x[1] + (y1 + 2 * y2 + 2 * y3 + 2 * y4) / 6;
        x[2] = x[2] + (y1 + 2 * y2 + 2 * y3 + 2 * y4) / 6;
        cout << x[1] << endl;
    }
}

注意变化

  • 您需要指定函数中变量的类型f(...)
  • 您需要在使用它们之前定义所有变量(一个好的规则是在使用之前指定所有内容,如果没有更改则添加 const 。
  • 请记住将要添加的变量初始化为零(y1,y2 ...等)

另外,我建议您使用 x1 而不是 x 1,因为您在 x 和 y 之间混合样式,并且您没有使用 zeroeth 元素。像这样

int main() {
    int i;
    float x1 = 1;
    float x2 = 2;
    float y1 = 0;
    float y2 = 0;
    float y3 = 0;
    float y4 = 0;
    const float h = 0.01;
    for (int i = 1; i <= 2; i++) {
        y1 = h * f(i, x1, x2);
        y2 = h * f(i, x1 + y1 / 2, x2 + y1 / 2);
        y3 = h * f(i, x1 + y2 / 2, x2 + y2 / 2);
        y4 = h * f(i, x1 + y3, x2 + y3);
        x1 = x1 + (y1 + 2 * y2 + 2 * y3 + 2 * y4) / 6;
        x2 = x2 + (y1 + 2 * y2 + 2 * y3 + 2 * y4) / 6;
        cout << x1 << endl;
    }
}

推荐阅读