目录
9.1
const int Len = 40;
//head.h
struct golf
{
char fullname[Len];
int handicap;
};
void setgolf(golf& g, const char* name, int hc);
//gold.cpp
void setgolf(golf& g,const char* name, int hc)
{
// g.fullname = name (错误)
strcpy(g.fullname, name);
g.handicap = hc;
}
//错误原因: g.fullname是字符串数组的数组名,其指向的是一个地址,相当于一个常量,不能给常量进行赋值
//解决方案: 1)使用cstring中包含的strcpy函数来赋值
2)通过一个循环来进行赋值
3)通过string来定义fullname
9.2
#include<string>
getline(cin,stringname)
//为string变量赋值可以用string中包含的getline函数
9.3
#include<new>
const int load = 100;
char Load[load];
struct chaff
{
char dross[20];
int slag;
};
chaff* s1 = new(Load)chaff[2];
//定位new运算符的基本语法: typename * name = new (loadname) typename
9.4
#pragma once
//head.h
namespace SALES
{
const int QUARTERS = 4;
struct Sales
{
double sales[QUARTERS];
double average;
double max;
double min;
};
void setSales(Sales& s, const double ar[], int n); //在main函数提供参数值(非交互版)
void setSales(Sales& s); //在函数中提供参数值 (交互版)
void showSales(const Sales& s);
}
//fuc.cpp
#include<iostream>
#include"head.h"
using namespace std;
namespace SALES
{
void setSales(Sales& s, const double ar[], int n)
{
double Max = 0;
double Min = 9999;
double total=0;
for (int i = 0; i < n; i++)
{
s.sales[i] = ar[i];
total += ar[i]; // 不可以 s.average = ar[i] / 4 :因为s.average是没有初始化的一个量,他的值是随机的
if (ar[i] > Max)
{
Max = ar[i];
}
if (ar[i] < Min)
{
Min = ar[i];
}
}
s.average = total / QUARTERS;
s.max = Max;
s.min = Min;
}
void setSales(Sales& s)
{
double Max = 0;
double Min = 9999;
double total=0;
cout << "请为数组赋值" << endl;
for (int i = 0; i < QUARTERS; i++)
{
cin >> s.sales[i];
total += s.sales[i];
}
s.average = total/QUARTERS;
for (int i = 0; i < QUARTERS; i++)
{
if (s.sales[i] > Max)
{
Max = s.sales[i];
}
if(s.sales[i] < Min)
{
Min = s.sales[i];
}
}
s.max = Max;
s.min = Min;
}
void showSales(const Sales& s)
{
for (int i = 0; i < QUARTERS; i++)
{
cout << "sales: " << s.sales[i] << endl;
}
cout << "averages:" << s.average << endl;
cout << "max: " << s.max << endl;
cout << "min: " << s.min << endl;
}
}
//源.cpp
#include<iostream>
#include"head.h"
using namespace std;
using namespace SALES;
int main()
{
Sales s[2];
double t[QUARTERS] = { 2,4,6,8 };
setSales(s[0],t, QUARTERS);
setSales(s[1]);
cout << "type one:" << endl;
showSales(s[0]);
cout << "type two:" << endl;
showSales(s[1]);
system("pause");
return 0;
}