如何在c++中使用函数
How to use functions in c++?
我应该得到以下代码来显示以下行的内容:"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;
}
我希望这能有所帮助。幕后还有很多事情要做,但这是基本的想法。祝你好运!:)
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗