
任何使用函数的编程语言都具有更简单、更模块化并且在调试时更容易更改的代码。函数是模块化代码中非常有用的组件。函数接受参数和输出结果的能力。函数不一定需要接受输入并始终产生结果。在许多情况下,函数只接受一些输入并且不返回任何内容。不总是回应,也不会容忍争议。本文将解释如何创建使用函数的 C++ 程序,函数接受多个参数并在处理后产生结果。
要定义一个带有几个参数的函数并向调用者函数返回一个值(调用者函数是调用我们的函数来执行某些操作的调用者函数),返回类型必须是特定类型,而不是 void ,并且参数列表中必须有给定的参数列表
<return type> function_name ( <type1> argument1, <type2> argument2, … ) {
// function body
}
在下面的示例中,我们将数字作为参数传递,然后计算给定数字的阶乘,并返回结果。让我们看看算法和 C++ 中的实现。
#include <iostream>
using namespace std;
long factorial( int n ) {
long fact = 1;
while ( n > 1 ) {
fact = fact * n;
n = n - 1;
}
return fact;
}
int main()
{
cout << "Factorial of 6 is: ";
long res = factorial( 6 );
cout << res << endl;
cout << "Factorial of 8 is: ";
res = factorial( 8 );
cout << res << endl;
cout << "Factorial of 12 is: ";
res = factorial( 12 );
cout << res << endl;
}
Factorial of 6 is: 720 Factorial of 8 is: 40320 Factorial of 12 is: 479001600
另一个使用函数检查数字是否回文的示例。我们传递一个数字作为参数,当它是回文时,函数将返回 true,当它不是回文时,函数将返回 false。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <sstream>
using namespace std;
string solve( int n ) {
int sum = 0;
int temp = n;
int rem;
while( n > 0) {
rem = n % 10;
sum = (sum * 10) + rem;
n = n / 10;
}
if( temp == sum ) {
return "true";
}
else {
return "false";
}
}
int main()
{
cout << "Is 153 a palindrome? " << solve( 153 ) << endl;
cout << "Is 15451 a palindrome? " << solve( 15451 ) << endl;
cout << "Is 979 a palindrome? " << solve( 979 ) << endl;
}
Is 153 a palindrome? false Is 15451 a palindrome? true Is 979 a palindrome? true
在编写代码时使用函数可以使代码模块化,并且在调试或使用别人的代码时有几个优点。有不同的函数模式,有时从调用者函数获取参数并将结果返回给调用者函数。有时它不接受任何输入但返回一个值。在本文中,我们通过几个示例了解了如何编写带有参数以及向调用者函数返回值的函数。使用函数非常简单且易于实现。在编写代码时使用函数总是好的,这样可以减少许多应用程序中不必要的代码重复。
以上就是C++程序创建一个带有参数和返回值的函数的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号