c++ - 函数'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]
如何在参数中操作不同数组的元素?
解决方案
我建议你尝试编译你的代码,编译器会给你一些重要的提示,说明什么是错误的。这是网上编译的代码。
为了使它编译,我将其更改为:
#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;
}
}
推荐阅读
- python - 在python3中编辑多个列表中的多个变量
- c# - 如何在聚合之前将值转换为 long?
- php - php laravel mailchimp curl请求不起作用
- spring - Neo4j 索引产生错误:运行查询时参考值未在偏移量 0 处初始化
- c# - 如何读取套接字流直到换行?
- javascript - 获取多个输入文件的图像预览
- ember.js - 在 javascript 文件中的 ember.js 中编辑数组
- embedded - Embedded Tcl:如何检测表达式的评估?
- laravel - 获取 Laravel Collection 上多维数组的总和
- java - java.io.FileNotFoundException:打开失败:ENOENT(没有这样的文件或目录)同时从 URL 读取图像