如何在c++中使用函数

How to use functions in c++?

本文关键字:函数 c++      更新时间:2023-10-16

我应该得到以下代码来显示以下行的内容:"1到10的和是55。"(较大的数字可以是我得到的任何数字。)我得到了这个代码。

#include <iostream>
using namespace std;
// Compute the sum of all of the numbers from 1 to n where n
// is a natural number
// use the formula: n(n+1)/2
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
int main()
{
int sum = 0;
int maxNumber;
// get the maxNumber for the function call
cout << "Enter a whole number greater than 0" << endl;
cin >> maxNumber;
// call compute sum
compute_sum(maxNumber); // Call to compute_sum function
// display the sum calculated by the compute_sum function
cout << "The sum of 1 to " << maxNumber;
cout << " is " << sum << endl;
return 0;
} 

我根本不明白函数是如何工作的,也不知道该如何实现。关于这件事,我唯一知道的是(这是老师说的),所需的改变并不重要。"注意:如果你正在对main和compute_sum函数进行重大更改,你可能就是做了太多的工作。"我曾尝试将函数更改为带返回的int函数,但我无法使其正常工作(很可能是因为不知道函数是如何工作的)。所以有人能帮我吗?

缺少的部分是函数的返回类型,然后实际从函数返回该值。

现在你有

void compute_sum(int limit) // compute_sum function
{
    int sum_to_limit;
    sum_to_limit = limit * (limit + 1) / 2;
}

C中的函数原型看起来很像这个

<return type> <name> (<parameters>)
{
    // your logic here
    return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}

你想修改你的函数,这样你就可以返回你在中计算的整数值

int compute_sum(int limit) // compute_sum function
{
    int sum_to_limit;
    sum_to_limit = limit * (limit + 1) / 2;
    return sum_to_limit;
}

因此,在主运行之后,当执行点到达时,会发生什么

compute_sum(maxNumber);

程序流跳转到该函数并执行其中的代码。当函数完成时,它会将值返回到最初调用的位置。所以你还需要添加这个来存储返回的值

int result = compute_sum(maxNumber);

然后确保将该值输出给用户。

你也可以让computer_sum函数更简洁一点,我不存储临时变量,你可以只做这个

int compute_sum(int limit) // compute_sum function
{
    return limit * (limit + 1) / 2;
}

我希望这能有所帮助。幕后还有很多事情要做,但这是基本的想法。祝你好运!:)