一、基本概念
1、变量:变量是存放一块数据的容器。变量有类型,用于描述变量所包含的数据的种类。c中的变量内置基本类型有int、unsigned int、float、char、double和long。
2、常量:一旦赋值后就不能改变的量。c中用const关键字声明。
3、枚举类型enum、类型定义typedef 。
4、函数:声明函数、返回值、参数、调用函数。
5、静态变量static、全局变量、局部变量。
6、条件语句、循环语句。
7、数组、多维数组、字符数组。
8、指针、函数与指针、const指针、动态存储。
9、结构体struct 、头文件
二、实例
#include <stdio.h>
#include <stdlib.h>
#include "MathFunctions.h"
#include "Song.h"
// global variables
int yearCount = 12;
int* allYears;
// utility functions
void setupYears();
int randomSongYear();
main ( int inputCount, char* inputValues[] ) {
// we don't want to count the program itself as a song name
int songCount = (inputCount - 1);
// tell the user how many song names they entered
if ( songCount > 0 ) {
printf ( "You entered %i song names \n", songCount );
} else {
printf ( "Didn't enter any song names. \n" );
exit(1);
}
// fill in the global 'allYears' array
setupYears();
// seed the random number generator,
// and get a random number
sranddev();
int randomNumber = rand() % 500;
// create an "easy" dynamic array of all of the songs,
// and a separate array of just the song lengths
Song allSongs[ songCount ];
int songLengths[ songCount ];
int i;
for (i = 0; i < songCount; i++) {
// choose a random length in seconds (up to 500)
// and a random song year
int length = rand() % 500;
int year = randomSongYear();
// get the song name
char* songName = inputValues[i+1];
// create the Song instance using all of the other values
allSongs[i] = createSong ( songName, length, year );
// finally, copy the length to the 'songLengths' array
songLengths[i] = length;
}
// display the total length of all songs
int combinedLength = sum (songLengths, songCount);
printf ("The total length of all songs is %i seconds\n", combinedLength);
// loop through the songs again and make an array of float values
float songLengthsAsFloats[ songCount ];
for (i = 0; i < songCount; i++) {
songLengthsAsFloats[i] = songLengths[i];
}
// calculate the average length
float averageLength = average (songLengthsAsFloats, songCount);
printf ("The average length is: %.2f seconds\n", averageLength);
// clean up the memory we malloc'd
free ( allYears );
}
void setupYears () {
// reserve memory for all of the year values. we can't use
// the "easy" dynamic array because 'years' is a global variable
allYears = malloc ( sizeof(int) * yearCount );
// choose the starting year
int oneYear = 2000;
// loop through and fill in each value
int i;
for ( i = 0; i < yearCount; i++ ) {
oneYear++;
allYears[i] = oneYear;
}
}
int randomSongYear () {
// get a random value between 0 and (yearCount-1)
int yearIndex = rand() % (yearCount-1);
// now use the index to get a year out of the 'allYears' array
int year = allYears[ yearIndex ];
return year;
}
三、小结