练习代码为本人所写,欢迎大家学习交流
若有疑问请留言,我将尽快回复!!!!
题8.1:
#include <iostream>
#include <ctime>
using namespace std;
void ShowStr(const char * str, int print_time = 1);
int main()
{
char str[100];
int time;
cout << "Enter the string: ";
cin.getline(str, 100);
cout << "Enter the time of show: ";
cin >> time;
ShowStr(str, time);
cout << endl;
ShowStr(str);
//以下是时延和回车读取,防止看不到结果
clock_t delay = 50 * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start <delay)
;
cin.get();
cin.get();
return 0;
}
void ShowStr(const char * str, int print_time) //记住定义函数的时候不写默认参数,而是在原型上默认
{
if(print_time > 0) //输入0次的时候则不显示
{
cout << str << " / ";
print_time--;
ShowStr(str, print_time);
}
}
题8.2:
#include <iostream>
#include <ctime>
using namespace std;
struct CandyBar
{
char name[128];
double weight;
int calorie;
};
void fill(CandyBar & candy_n, char * name_n, double weight_n, int calorie_n);
void show(const CandyBar & candy_n);
int main()
{
CandyBar candy1;
fill(candy1, "Millennium Munch", 2.85, 350);
show(candy1);
//以下是时延和回车读取,防止看不到结果
clock_t delay = 50 * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start <delay)
;
cin.get();
cin.get();
return 0;
}
void fill(CandyBar & candy_n, char * name_n, double weight_n, int calorie_n)
{
strcpy(candy_n.name, name_n); //实验证明C++使用strcpy函数是不用包含头文件<cstring>的
candy_n.weight = weight_n;