宏定义和const常量定义
#include<stdio.h>
#include<math.h>
#define PI 3.1415926 //宏定义
int main()
{
int r;
float area,volume;
printf("Please enter r:");
scanf("%d",&r);
area = 4*PI*pow(r,2);
volume = 4*PI*pow(r,3) / 3;
printf("area = %f,volume = %f", area, volume);
return 0;
}
#include<stdio.h>
#include<math.h>int main()
{
int r;
float area,volume;
const double PI = 3.1415926; //const常量
printf("Please enter r:");
scanf("%d",&r);
area = 4*PI*pow(r,2);
volume = 4*PI*pow(r,3) / 3;
printf("area = %f,volume = %f", area, volume);
return 0;
}
错误1
#include<stdio.h>
#include<math.h>
int main()
{
float myHeight,faHeight,moHeight;
char sex,sports,diet;
printf("Please onput faHeight:");
scanf("%.1f",&faHeight);
printf("Please input moHeight:");
scanf("%.1f",&moHeight);
printf("Are you a boy or girl?(F/M)"); //总是运行不对 , 用 / 而不是 \
scanf(" %c",&sex); //换行符用 \
printf("Do you like sports?(Y/N)");
scanf(" %c",&sports);
printf("Do you have a good diet?(Y/N)");
scanf(" %c",&diet);
if(sex=='F'||sex=='f')
{
myHeight=(faHeight*0.923+moHeight)/2;
}
else
{
myHeight=(faHeight+moHeight)*0.54;
}
if(sports=='Y'||sports=='y')
{
myHeight*=1+0.02;
}
else
{
myHeight=myHeight;
}
if(diet=='Y'||diet=='y')
{
myHeight*=1+0.015;
}
else
{
myHeight=myHeight;
}
printf("myHeight=%f",myHeight);
return 0;
}
错误二
赋值和判等
生成随机数
methoth 1:
unsigned int seed;
printf("Please enter a seed:");
scanf("%u",&seed); //无符号整型变量用 %u
srand(seed);
int magic = rand() % 100 + 1; //生成一个 1 到 100 的随机数
method 2:
srand( time(NULL) ); //通过函数time()读取计算机的时钟值,设为随机数种子
int magic = rand() % 100 + 1; //使用函数time(),头文件要包括<time.h>
增强程序的健壮性
int magic, guess;
int ret; //用于保存scanf()的返回值
srand( time (NULL) )
magic = rand() % 100 + 1;
printf(" Please enter a magic number:");
ret = scanf (" %d ", &guess);
while( ret != 1 ) //若存在输入错误,则重新输入
{
while ( grtchar() != '\n' ); //清除输入缓冲区中的非法字符
printf("Please enter a magic number:");
ret = scanf(" %d ", &guess);
}