【问题标题】:How to use functions in c++?如何在 C++ 中使用函数?
【发布时间】:2015-03-04 23:30:04
【问题描述】:

我应该得到以下代码来显示类似以下内容的内容:“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 函数,但我无法让它正常工作(很可能是因为不知道函数是如何工作的)。所以有人可以帮我吗?

【问题讨论】:

  • 您说您尝试了“int 函数”。你的意思是函数应该返回一个int。这应该是要走的路。您可以发布您尝试过的更改代码吗?
  • int variable = functionthatreturnsint(whatever);?
  • 你需要让compute_sum返回它计算的值。
  • 如果您正在向人类讲师学习,则需要与讲师交谈。了解编写和使用函数是本作业的先决条件。 如果您不了解需求,请在开始之前与创建需求的人交谈。

标签: c++ function return-value


【解决方案1】:

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

现在你有

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;
}

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

【讨论】:

  • 我将其更改为具有 int 而不是 void 并在函数中返回 sum_to_limit 但我不确定将结果放在哪里 = compute_sum(maxNumber) 在 compute_sum(maxNumber?
  • 您应该将compute_sum(maxNumber) 替换为int result = compute_sum(maxNumber)。您需要新的 int 变量来存储函数的结果。然后您可以致电cout &lt;&lt; "The sum of 1 to " &lt;&lt; result; 这应该可以工作
  • 非常感谢,我知道这确实是一个我应该已经知道的问题,但这非常有帮助,我并不是想用它作为家庭作业的快速答案,我真的不知道怎么做使用那么多函数。
  • 没问题!功能是无价的。我希望解释有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多