C语言
1、打印白菜、萝卜、西红柿每斤的价格及购买数量,统计一共花的钱数,并打印屏幕。(数据结构+算法)
设计数据结构(像设计数据库的字段类型一样,考虑最佳使用类型):
蔬菜名字:字符串常量数组
const char* radish = “萝卜”;(驼峰式的编码规范)
价格:浮点数单精度float
float radishPrice = 1.68f;
购买数量:整型int(数量肯定没有负值,用unsigned修饰)
unsigned int radishWeight = 2;
总价格:浮点数单精度float
float totalPrice = 0.0f;
设计算法(设计函数):
设计一个打印蔬菜信息的函数(注意函数的扩展性)
void printVegetableInfo(const char* name[], float *price, int weight, int count);
简单描述算法:
1、根据count遍历 name price weight 打印信息出来,并计算每一种蔬菜的总价格
2、每一种蔬菜的总价格作为calTotalPrice的输入参数,计算返回总价格
3、打印总价格
设计一个计算总费用的函数
float calTotalPrice(float *vegTotalPrice, int count);
1、根据count遍历vegTotalPrice求和
2、返回第一步求取的和
#include <stdio.h>
#define VEGECOUNT 3
/*打印蔬菜信息*/
void printVegetableInfo(const char* vegeName[], float *price, int *weight, int count);
/*计算总费用的函数*/
float calTotalPrice(float *vegTotalPrice, int count);
int main()
{
const char* vegeName[VEGECOUNT] = {"白菜","萝卜","西红柿"};
float vegePrice[VEGECOUNT] = {1.68,4.50,3.58};
unsigned int vegeWeight[VEGECOUNT] = {2,6,9};
printVegetableInfo(vegeName,vegePrice,vegeWeight,VEGECOUNT);
return 0;
}
void printVegetableInfo(const char* name[], float *price, int *weight, int count)
{
float totalPrice = 0.0;
float vegePrice[VEGECOUNT] = {0.0};
printf("名字:");
for (int i = 0; i < count; i++)
{
printf("%7s",name[i]);
}
printf("\n");
printf("价格:");
for (int i = 0; i < count; i++)
{
printf("%-5.2f",price[i]);
}
printf("\n");
printf("数量:");
for (int i = 0; i < count; i++)
{
printf("%3d",weight[i]);
}
printf("\n");
for (int i = 0; i < count; i++)
{
vegePrice[i] = price[i] * weight[i];
}
totalPrice = calTotalPrice(vegePrice,VEGECOUNT);
printf("总价:%.2f",totalPrice);
}
float calTotalPrice(float *vegTotalPrice, int count)
{
float totalPrice = 0.0;
for (int i = 0; i < count; i++)
{
totalPrice += vegTotalPrice[i];
}
return totalPrice;
}
2、用户从键盘输入任意的字符串(小于127有效字符,大于的话后边的丢弃了);统计一下用户输入字符串中的数字个数,小写字母个数,大写字母个数,其他字符的个数,将字符串中所有的小写字符,全部转化成大写字母并退出。
把特殊字符(数字和字母以外)去除,形成新的字符串数组,输出。
1、新建一个数组,char tempstr[128];
2、遍历inputstr,如果变量的字母不是other情况,就依次保存到tempstr数组中
3、遍历完成后,需要在tempstr保存的有效字母的最后一个之后添加一个字符串结束标记’\0’。
设计数据结构(就像数据库字段一样,考虑最佳数据类型):
输入的字符串:字符串数组 char* str = NULL;
字符串中的数字个数:
unsigned int strNumberCount = 0;
字符串中小写字母个数:
unsigned int strSmallCount = 0;
字符串中大写字母个数:
unsigned int strUpperCount = 0;
其他字符个数:
unsigned int strOtherCount = 0;
有5个学生,学习4门课程,已知所有学生的各科成绩,编程:分别求每个学生的平均成绩和每门课程的平均成绩
设计数据结构(就像数据库字段一样,考虑最佳数据类型)
学生的数据结构:
typedef struct Student{
char name[32];
float score[4];
}Student_st;
课程的数据结构
typedef struct{
char name[32];
float score;
}Course_st
班级学生的数据结构
Stundent_st[5] = {
{“zhangsan”,{60.0,70.0,60.0,70.0,80.0},
{“lisi”,{60.0,70.0,60.0,70.0,90.0},
{“wangwu”,{60.0,70.0,60.0,80.0,80.0},
{“xuliu”,{40.0,70.0,60.0,70.0,80.0},
{“caiqi”,{50.0,70.0,60.0,70.0,80.0} //最后一个元素不要打逗号(怕程序员没写完漏了)
};