为了更好地理解函数中的参数和返回值,用户定义的函数可以有多种形式,例如:
不传参数,无返回值
#include <iostream>
using namespace std;
// declare a function
// with no arguments and no return value
void say_hello();
int main() {
// no argument is passed to the function
say_hello();
return 0;
}
void say_hello() {
cout << "Hello!";
}
输出
Hello!
这里,
- 我们没有向
say_hello()
传递任何参数。 say_hello()
的返回类型是void
,所以它不返回任何值。
不传参数,但有返回值
#include <iostream>
using namespace std;
// declare a function with no arguments
// and return type string
string get_username();
int main() {
// call prime and assign return value to is_prime
string user_name = get_username();
cout << "Hello, " << user_name;
}
string get_username() {
string name;
cout << "Enter your user name\n";
cin >> name;
return name;
}
输出
Enter your user name : John Hello, John
这里,
- 我们没有向
get_username()
传递任何参数。 get_username()
的返回类型是 string,所以它返回用户输入的 name。
get_username()
函数接收用户输入的姓名,并返回该姓名。
main()
函数根据 get_username()
返回的值输出结果。
传递参数,无返回值
#include <iostream>
using namespace std;
void say_hello(string name);
int main() {
cout << "Enter your name: ";
string name;
cin >> name;
// pass argument num function prime()
say_hello(name);
}
void say_hello(string name) {
cout << "Hello " << name ;
}
输出
Enter your name: John Hello John
这里,
- 我们向
say_hello(string)
传递了一个 string 类型的参数。 say_hello()
的返回类型是void
,所以它不返回任何值。
main()
函数使用参数 name 调用 say_hello()
。
传递参数,有返回值
#include <iostream>
using namespace std;
// declare a function
// with int argument and int return type
bool check_prime(int n);
int main() {
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
int is_prime = check_prime(num);
if (is_prime == true)
cout << num << " is a prime number.";
else
cout << num << " is not a prime number.";
return 0;
}
// function to check if the number is prime
bool check_prime(int n) {
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
return false;
}
for (int i = 2; i <= n/2; ++i) {
if (n % i == 0)
return false;
}
return true;
}
输出
Enter a positive integer to check: 14 14 is not a prime number.
这里,
- 我们向
check_prime()
传递了一个 int 类型的参数。 check_prime()
的返回类型是bool
,所以它返回true
或false
。
main()
函数使用参数 num 调用 check_prime()
。
如果数字是素数,check_prime()
返回 true
,否则返回 false
。然后 main()
根据 check_prime()
返回的值输出结果。
另请阅读