函数基础
练习
练习6.6
1 #include<iostream> 2 using namespace std; 3 4 double myADD(double num1, double num2) 5 { 6 double result = num1 + num2; 7 static unsigned iCnt = 0; 8 ++iCnt; 9 cout << "该函数累计执行了" << iCnt << "次" << endl; 10 return result; 11 } 12 13 int main() 14 { 15 double num1, num2; 16 cout << "请输入两个数:"; 17 while (cin >> num1 >> num2) 18 { 19 cout << num1 << "与" << num2 << "的求和结果:" 20 << myADD(num1, num2) << endl; 21 } 22 return 0; 23 }
运行结果:
练习6.7
1 #include<iostream> 2 using namespace std; 3 4 unsigned myCnt() 5 { 6 static unsigned iCnt = -1; 7 ++iCnt; 8 return iCnt; 9 } 10 int main() 11 { 12 cout << "请输入任意字符按回车键任意键" << endl; 13 char ch; 14 while (cin >> ch) 15 { 16 cout << "函数myCnt的执行次数:" << myCnt() << endl; 17 } 18 return 0; 19 }
参数传递
•使用引用避免拷贝
bool isShorter(const string &s1, const string &s2) { return s1.siz2() < s2.size(); }
•使用引用形参返回额外信息
//返回s中c第一次出现的位置 //引用形参occurs负责统计c出现的次数 string::size_type find_char(const string &s, char c, string::size_type &occurs) { auto ret = s.size(); occurs = 0 for(decltype(ret) i = 0; i != size(), ++i) { if(s[i] == c) { if(ret == s.size()) ret = i; ++occurs; } } return ret; } auto = find_char(s, ‘o‘, ctr);
练习
练习6.11
1 #include<iostream> 2 using namespace std; 3 4 int reset(int &i) 5 { 6 i = 0; 7 return i; 8 } 9 10 int main() 11 { 12 int num = 10; 13 cout << "重置前:num = " << num << endl; 14 reset(num); 15 cout << "重置后:num = " << num << endl; 16 return 0; 17 }
原文地址:https://www.cnblogs.com/sunbines/p/8715703.html
时间: 2024-10-10 00:47:20