【发布时间】: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