C++ 结构数组+循环 简单例题1
C++ 结构数组+循环 简单例题1
菜鸡做的简单例题,自用笔记。
题目
为每个顾客分配一个顾客号(从0开始) ,定义一个数组用来记录每天每位顾客的购买额,数组下标正好与顾客号相对应。接待完当天最后一位顾客后,输出每位顾客的顾客号与购买额、总的购买额及每位顾客的平均购买额。
思想
- 定义数组;
- 顾客、顾客号、购买额;
- 一个顾客对应一个顾客号,购买额相叠加;
- 无限循环直到店铺打烊(即购买额为0);
- 输入、输出具有可读性;
1. 定义结构数组
#include<iostream>
#include<cstring>
using namespace std;
struct Customer
{
char name[10];
int num;
};
Customer cus[100];
2. 输入名字和金额
*注意一个名字对应一个顾客号
int main()
{
int i=0,j=0,num;
char name[10];
float parchase[100],money;
while(true) //无限循环。可以输入多个顾客
{
cout<<"the total price is ";
cin>>money;
if(money==0) //循环停止条件,店铺打烊
break;
cout<<"the customer's name is ";
cin>>name;
for(j=0;j<=i;j++) //循环,以与前面存入的名字比较
{
if(0==strcmp(cus[j].name,name)) //判断是否与前面的循环有重复
{
parchase[j]+=money;
cout<<"the number of "<<cus[j].name
<<" is "<<cus[j].num<<"\n";
cout<<"the parchase is "<<parchase[j]<<"\n"<<endl;
break;
}
else if(j==i) //循环到最后一次仍然没有发现名字已存,就把名字存到新的顾客号里
{
strcpy(cus[i].name,name);
cus[i].num=i;
parchase[i]=money;
cout<<"the number of "<<cus[i].name<<" is "<<cus[i].num<<"\n";
cout<<"the parchase is "<<parchase[i]<<"\n"<<endl;
i++;
break; //不跳出会有错误
}
}
}
3.输出
很简单的循环输出下每个顾客,求和算平均值就ok
float sum=0,ave;
if(i!=0)
{
cout<<"today's the parchase is"<<endl;
for(j=0;j<i;j++)
{
cout<<"["<<cus[j].num<<"]"<<cus[j].name<<":"<<parchase[j]<<"元; ";
sum=sum+parchase[j];
}
cout<<endl;
cout<<"the total is "<<sum<<"元."<<endl;
ave=sum/i;
cout<<"the average is "<<ave<<"元."<<endl;
}
else
cout<<"No guest today."<<endl;
}
结果大概这样:
tips
- 判断两个字符数组是否完全相同
#include<cstring>
strcmp(const char *s1,const char *s2)
- 无限循环
设置条件,break跳出
- 字符数组的赋值
strcpy(str1,str2) //将str2赋给str1
注:在本题中,把string类型的name赋给字符数组会报错,原因不明;
(个人怀疑是因为输入的name长度不确定,系统不确定字符数组是否能容纳下,故报错)
但可以把字符数组name赋给字符数组。
另:本解输出没大问题,但是逻辑有些问题且未优化。