[英]Write a sum function that returns the sum of all the elements of the array
#include <iostream>
#include<math.h>
using namespace std;
struct Point { //B
double x = 0;
double y = 0;
};
void fillArray(double box[][10]) { //D
cout << "Insert 100 doubles: ";
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
cin >> box[i][j];
}
}
}
int sum(int* arr, int size) { //f
int result = 0;
for (int i = 0; i < size; ++i)
result += arr[i];
return result;
}
int main() {
double box[10][10]{}; //A
cout << "Enter your name:";
//C
string name;
cin >> name;
cout << "Hello " << name << '\n';
fillArray(box);
}
I am having troubles making a couple other functions.我在制作其他几个功能时遇到了麻烦。
G)Write a difference function that receives as parameter 2 elements of the array and which returns the difference between element a and element b. G)编写一个差值函数,该函数接收数组的 2 个元素作为参数,并返回元素 a 和元素 b 之间的差值。
this is the first function I do not understand.这是我不明白的第一个功能。
H)Write a product function that receives as parameter 2 elements of the array and which returns the product of these elements. H)编写一个乘积函数,该函数接收数组的 2 个元素作为参数,并返回这些元素的乘积。
This is my advice: Clear your basics and everything will be okay.这是我的建议:清除您的基础知识,一切都会好起来的。
This is my code:这是我的代码:
Version 1 : For summing all elements of the array:版本 1 :用于对数组的所有元素求和:
#include <iostream>
double sum(double *arr, std::size_t lengthArr )
{
double sum = 0;
for(int i = 0; i < lengthArr; ++i)
{
sum += arr[i];
}
//return the sum
return sum;
}
int main()
{
//create the array
double arr[] = {1, 10, 13, 43,43,543,63};
std::cout<<"The sum is: "<<sum(arr, sizeof(arr)/sizeof(double));//call the sum fuction passing the arr and its size
return 0;
}
Version 2 : For writing a product function that receives as parameter 2 elements of the array and which returns the product of these elements.版本 2 :用于编写一个乘积函数,该函数接收数组的 2 个元素作为参数,并返回这些元素的乘积。
#include <iostream>
double product(double &a, double &b )//a and b are passed by reference
{
//return the product
return a * b;
}
int main()
{
//create the array
double arr[] = {1, 10, 13, 43,43,543,63};
std::cout<<"The product is: "<<product(arr[1], arr[3]);//call the product function and pass whichever elements of the array
return 0;
}
I suppose you can modify version 2 for subtraction purpose.我想您可以为减法目的修改第 2 版。
Note that we can also use templates to make this program more general.请注意,我们还可以使用模板使该程序更通用。 These samples were just to get you started(or as a reference).
这些示例只是让您入门(或作为参考)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.