阿稳自修室P45:函数参数和按值传递
  1. 用于接收传递值的变量被称为形参(参量parameter),传递给函数的值称为实参(参数argument)
  2. 有多个参数时,调用函数时只需要用逗号将参数分开,若类型相同必须分别指定每个参数的类型

程序清单7.3 twoarg.cpp

一个接受两个参数的函数,表明在函数中修改形参的值不会影响调用程序中的数据。

#include<iostream>
void n_chars(char c, int n);
int main()
{
	using namespace std;
	int times;
	char ch;
	cout << "Enter a character: ";
	cin >> ch;
	while (ch != 'q')
	{
		cout << "Enter an integer: ";
		cin >> times;
		n_chars(ch, times);
		cout << "\nEnter another character or press the q-key to quit: ";
		cin >> ch;
	}
	cout << "times in main() is " << times << ".\n";
	cout << "Bye\n";
	return 0;
}
void n_chars(char c, int n)
{
	while (n-- > 0)
		std::cout << c;
}

程序清单7.4 lotto.cpp

#include<iostream>
long double probability(unsigned numbers, unsigned picks);
int main()
{
	using namespace std;
	double total, choices;
	cout << "Enter the total number of choices on the game card and\n"
		"the number of picks allowed:\n";
	while (cin >> total >> choices && choices <= total)
	{
		cout << "You have one chance in ";
		cout << probability(total, choices);
		cout << " of winning.\n";
		cout << "Next two numbers(q to quit): ";
	}

	cout << "bye\n";

	return 0;
}

long double probability(unsigned numbers, unsigned picks)
{
	long double result = 1.0;
	long double n;
	long double p;
	for (n = numbers, p = picks; p > 0; n--, p--)
		result *= n / p;
	return result;
}

在函数头中定义了形参,函数内部还定义了其他变量,作用域都在函数内部,形参与局部变量的区别在于,形参从main()函数中得到实参的值,函数体内部的局部变量是从函数中得到自己的值。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇