前言
本章主要内容介绍
关键字——if、else、......goto
运算符——&&、||、?:
函数
switch
getchar()以及putchar()
ctype.h头文件函数系列
一、if语句
if语句的通用形式如下
if(expression)
statement
如果表达式expression为真,则执行statement,反之则跳过。
statement语句可以是一条简单语句,也可以是复合语句。
if(score>big)
{
prntf("Jackpot!");
}
if (joe>ron)
{
joecash++;
printf("You lose,Ron\n");
}
即,statement部分即使由复合语句构成,但整个if语句仍被视为一条语句。
if else 语句
通用形式如下
if (expression)
statement
else
statement2
如果expression为真则执行statement,否则执行statement2.很好理解。
二、字符输入/输出函数
getchar以及putchar函数
getchar()函数不带任何参数,它从输入队列中返回下一个字符。
ch=getchar();
与
scanf("%c",&ch)
是等价的,也就是说可以利用getchar函数读取字符;
putchar()函数打印他的参数
下面的语句同样是等价的
putchar(ch);
printf("%c",ch);
多重选择语句else if
if (score<1000)
bouns=0;
else if(score<1500)
bouns=1;
else if(score<2000)
bouns=2;
else if(score<2500)
bouns=4;
else
bouns=6;
else 与if 语句的配对
在没有花括号的时候,规则是else与离他最近的if匹配
多层嵌套的if语句
下面看一个示例:寻找素数
#include <stdio.h>
int main()
{
unsigned long num;
unsigned long div;
bool isprime;
printf("Please input an integer :\n");
while(scanf("%lu",&num)==1)
{
for(div=2,isprimer=true;(div*div)<=num;div++0
{
if(num%div ==0)
{
if((div*div)!=num)
printf("%lu is divisible by %lu and %lu.\n",num,div,num/div);
else
printf("%lu is divisible by %lu.\n",num,div);
isprime=false;
}
}
if (isprime)
{
printf("%lu is a prime");
}
return 0;
}
逻辑运算符
在C语言中,逻辑运算符有&&、||、!
&&表示“与”的意思,需要两端的表达式的值都为true,该式的值才为true。
||表示“或”的意思,两端的表达式的值只要有一端为true,该式的值就为true。
!表示“非”的意思,将该式的真值换成相反的真值,即false和true互换。
但是在C99里有这样的一个名为“短路”的特性
使用&&时,如果左边false则右边不会执行
使用||时,如果左边true则右边不会执行
条件运算符
条件运算符是C语言中唯一的三元运算符。
其通用形式如下:
expression1 ? expression2 : expression3
如果expression1为真,整个条件表达式的值是expression2的值;否则,是expression3的值。
x = (y<0) ? -y : y;
可以用if else表达
If (y < 0)
x = -y;
else
x = y;
通常,条件运算符完成的任务用 if else 语句也可以完成
示例:
(6>4) ? 1:2 值为1
(4>6) ? 1:2 值为2
continue 和break
break:
1.只能在for、while、do…while,循环语句中和switch语句体内使用break。
2. break用于跳出一个循环或一个switch,若多个循环,即结束本层的一个循环体。
continue:
1. 跳过本次循环体中剩下尚未执行的语句,立即进行下一次的本循环条件判定,可以理解为只是中止(跳过)本次循环,接着开始下一次本循环。
区别如下
(1)、break语句是终止本层循环(但不影响下一次循环),而continue语句并没有使本层循环终止。
(2)、当在非switch语句中遇到break时,是直接跳出本层循环体,然后继续执行本层循环体外后面的代码,当非switch语句中遇到continue时,是立即跳到本层循环体进行重新条件判断的,且并不往下执行本层循环体后面的代码。
(3)、当在switch语句中遇到break时,是跳出本层的switch语句(即所在的一个switch),而非跳出循环体,当在switch语句中遇到continue时,是立即跳到本层循环体进行重新条件判断的,且并不往下执行本层循环体后面的代码。注意:
continue在非switch语句或switch语句中,作用和效果都是一样的。break在非switch语句和switch语句中,作用和效果是有所区别的。
switch语句
下面见一个示例:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf(“Give me a letter of the alphabet, and I will give ”);
printf("an animal name/nbegining with that letter .\n");
printf("Please type in a letter; type # to end my act");
while ((ch=getchar()!='#')
{
if('\n'==ch)
continue;
if (islower(ch))
switch(ch)
{
case 'a':
printf("......");
break;
case 'b':
printf(".....");
break;
case 'c':
printf("......");
case 'd':
break;
printf(".....");
break;
defult:
printf(".......");
}
while(getchar()!='\n')
{
}
return ;
}
这只是一个简单的小程序,作为switch语句的介绍,在书上也有完整版详细代码,完成的是对于输入字母的识别以及使用while语句跳过输入行,只读取识别首字母的功能。
swtich(表达式) { // ()中的数据类型仅仅支持整数
case 常量1 :
要执行的语句;
break;
case 常量2 :
要执行的语句;
break;
case 常量3 :
要执行的语句;
break;
default:
要执行的语句;
break;
}
goto语句
原则上不需要在c程序中使用goto语句,但是C程序员可以接受一种goto的用法——出现问题的时候从一组嵌套循环中跳出(一条break语句只能跳出当前循环)。
while(funct>0)
{
for(i=1;i<=100;i++)
{
statement;
if(question)
goto help;
statement;
}
}
help: statement3;
编程练习
1.
#include <stdio.h>
int main(void)
{
int ch, space, enter, others;
space = enter = others = 0;
printf("Please enter some characters ('#' to quit):\n");
while ((ch = getchar()) != '#')
{
if (ch == ' ')
{
space++;
}
else if (ch == '\n')
{
enter++;
}
else
{
others++;
}
}
printf("Here are the messages\n");
printf("Space: %d\n", space);
printf("Linefeed: %d\n", enter);
printf("Others: %d\n", others);
return 0;
}
2.
#include <stdio.h>
#define STOP '#'
int main(void)
{
int ch;
int i = 0;
printf("Enter some characters('#' to quit):\n");
while ((ch = getchar()) != STOP)
{
if (i++ % 8 == 0)
{
putchar('\n');
}
if (ch == '\n')
{
printf("'\\n'-%3d ", ch);
}
else if (ch == '\t')
{
printf("'\\t'-%3d ", ch);
}
else
{
printf("'%c'-%3d ", ch, ch);
}
}
printf("Done.\n");
return 0;
}
3.
#include <stdio.h>
int main(void)
{
int n, odd, even;
int e_sum, o_sum;
odd = even = 0;
e_sum = o_sum = 0;
printf("Please enter a integer (0 to quit): ");
while (scanf("%d", &n) == 1 && (n != 0))
{
if (n % 2 == 0)
{
even++;
e_sum += n;
}
else
{
odd++;
o_sum += n;
}
printf("You can enter again (0 to quit): ");
}
printf("Even number: %d\n", even);
if (even > 0)
{
printf("The average of even: %g\n", (float)e_sum / even);
}
printf("Odd number: %d\n", odd);
if (odd > 0)
{
printf("The average of odd: %g\n", (float)o_sum / odd);
}
printf("Done.\n");
return 0;
}
4.
#include <stdio.h>
#define STOP '#'
int main(void)
{
int ch;
int n = 0;
printf("Enter some characters('#' to quit):\n");
while ((ch = getchar()) != STOP)
{
if (ch == '.')
{
putchar('!');
n++;
}
else if (ch == '!')
{
printf("!!");
n++;
}
else
{
putchar(ch);
}
}
printf("\nTotal replace %d times.\n", n);
printf("('.'->'!') or ('!'->'!!').\n");
return 0;
}
5.
#include <stdio.h>
#define STOP '#'
int main(void)
{
int ch;
int n = 0;
printf("Enter some characters('#' to quit):\n");
while ((ch = getchar()) != STOP)
{
switch (ch)
{
case '.':
{
putchar('!');
n++;
break;
}
case '!':
{
printf("!!");
n++;
break;
}
default:
{
putchar(ch);
}
}
}
printf("\nTotal replace %d times.\n", n);
printf("('.'->'!') or ('!'->'!!').\n");
return 0;
}
6.
#include <stdio.h>
#define STOP '#'
int main()
{
char ch;
int a,num;
while((ch=getchar())!=STOP)
{
switch(ch)
{
case 'e':
num=1;
break;
case 'i':
if(num==1)
{
a++;
}
else
num=0;
break;
defult :
num=0;
}
}
printf("%d",a);
return 0;
}
7.
#include <stdio.h>
#define TIMES 1.5
#define BASE 10
int main()
{
float total,tax_revenue,net_income;
int hours;
printf("Please input your work hours in a week:");
scanf("%d",&hours);
if(hours>40)
{
total=400+1.5*hours*BASE;
if(total>450)
{
tax_revenue=300*0.15+150*0.2+(total-450)*0.25;
}
else
{
tax_revenue=300*0.15+(total-300)*0.2;
}
printf("total=%f$\ntax=%f$\nnet=%f$\n",
total,tax_revenue,(total-tax_revenue));
}
else
{
total=hours*BASE;
if(total>300)
{
tax_revenue=300*0.15+(total-300)*0.2;
}
else
{
tax_revenue=total*0.15;
}
printf("total=%f$\ntax=%f$\nnet=%f$\n",
total,tax_revenue,(total-tax_revenue));
}
return 0;
}
8.
#include <stdio.h>
const double TIME1 = 8.75;
const double TIME2 = 9.33;
const double TIME3 = 10.00;
const double TIME4 = 11.20;
#define RATE1 0.15
#define RATE2 0.20
#define RATE3 0.25
double total, tax_revenue, net_income;
int hours;
void out(int a);
void salary(int h, const double BASE);
int main()
{
int i;
printf("****************************************************************************************\n");
printf("Enter the number corresponding to the desired pay rate or action:\n");
printf("1) 8.75 /hr 2) 9.33 /hr\n");
printf("3) 10.00 /hr 4) 11.20 /hr\n");
printf("5) quit\n");
printf("****************************************************************************************\n");
top: while (scanf_s("%d", &i))
{
if (i == 5)
{
printf("Please input the correct number from 1 to 4!\n");
goto top;
}
else
{
printf("Please input your work hours in a week:");
scanf_s("%d", &hours);
out(i);
continue;
}
return 0;
}
}
void salary(int h, const double BASE)
{
if (h > 40)
{
total =(double) (400 + 1.5 * h * BASE);
if (total > 450)
{
tax_revenue = 300 * RATE1 + 150 * RATE2 + (total - 450) * RATE3;
}
else
{
tax_revenue = 300 * RATE1 + (total - 300) * RATE2;
}
}
else
{
total = (double)h * BASE;
if (total > 300)
{
tax_revenue = 300 * RATE1 + (total - 300) * RATE2;
}
else
{
tax_revenue = total * RATE1;
}
}
printf("total=%f$\ntax=%f$\nnet=%f$\n",
total, tax_revenue, (total - tax_revenue));
return;
}
void out(int a)
{
switch (a)
{
case 1:
salary(hours, TIME1);
break;
case 2:
salary(hours, TIME2);
break;
case 3:
salary(hours, TIME3);
break;
case 4:
salary(hours, TIME4);
break;
defult:
printf("Please input the correct number from 1 to 4!\n");
}
}
9.
#include <stdio.h>
#include <math.h>
int main(void)
{
int i, n, number, prime;
printf("Please enter a number (<= 0 to quit): ");
while (scanf("%d", &number) == 1 && (number > 0))
{
if (number == 1)
{
printf("1 isn't a prime!\n");
printf("You can enter again (<= 0 to quit): ");
continue;
}
printf("Here are the prime (<= %d):\n", number);
for (i = 2; i <= number; i++)
{
prime = 1;
for (n = 2; n <= sqrt(i); n++)
{
if (i % n == 0)
{
prime = 0;
break;
}
}
if (prime)
{
printf("%-3d", i);
}
}
printf("\nYou can enter again (<= 0 to quit): ");
}
printf("Done.\n");
return 0;
}
10.
#include <stdio.h>
#define PLAN1 17850
#define PLAN2 23900
#define PLAN3 29750
#define PLAN4 14875
#define RATE1 0.15
#define RATE2 0.28
int main(void)
{
int n;
double wage, tax;
while (1)
{
printf("********************************\n");
printf("1) single\n");
printf("2) householder\n");
printf("3) married\n");
printf("4) married but divorced\n");
printf("5) quit\n");
printf("********************************\n");
printf("Please you choose: ");
while (scanf("%d", &n) != 1 || (n > 5 || n < 1))
{
while (getchar() != '\n')
continue;
printf("Please enter 1, 2, 3, 4 or 5: ");
}
if (n != 5)
{
printf("Please enter your wage: ");
scanf("%lf", &wage);
}
if (1 == n)
{
if (wage <= PLAN1)
{
tax = wage * RATE1;
}
else
{
tax = PLAN1 * RATE1 + (wage - PLAN1) * RATE2;
}
printf("Your tax: %g\n\n", tax);
}
else if (2 == n)
{
if (wage <= PLAN2)
{
tax = wage * RATE1;
}
else
{
tax = PLAN2 * RATE1 + (wage - PLAN2) * RATE2;
}
printf("Your tax: %g\n\n", tax);
}
else if (3 == n)
{
if (wage <= PLAN3)
{
tax = wage * RATE1;
}
else
{
tax = PLAN3 * RATE1 + (wage - PLAN3) * RATE2;
}
printf("Your tax: %g\n\n", tax);
}
else if (4 == n)
{
if (wage <= PLAN4)
{
tax = wage * RATE1;
}
else
{
tax = PLAN4 * RATE1 + (wage - PLAN4) * RATE2;
}
printf("Your tax: %g\n\n", tax);
}
else if (5 == n)
{
break;
}
}
printf("Done.\n");
return 0;
}
11.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const double price_artichokes = 2.05;
const double price_beets = 1.15;
const double price_carrots = 1.09;
const double DISCOUNT_RATE = 0.05;
const double under5 = 6.50;
const double under20 = 14.00;
const double base20 = 14.00;
const double extralb = 0.50;
int ch;
double lb_artichokes = 0;
double lb_beets = 0;
double lb_carrots = 0;
double lb_temp;
double lb_total;
double cost_artichokes;
double cost_beets;
double cost_carrots;
double cost_total;
double final_total;
double discount;
double shipping;
printf("Enter a to buy artichokes, b for beets, ");
printf("c for carrots, q to quit: ");
while ((ch = tolower(getchar())) != 'q')
{
if (isspace(ch))
{
continue;
}
while (getchar() != '\n')
continue;
switch (ch)
{
case 'a':
{
printf("Enter pounds of artichokes: ");
scanf("%lf", &lb_temp);
lb_artichokes += lb_temp;
break;
}
case 'b':
{
printf("Enter pounds of beets: ");
scanf("%lf", &lb_temp);
lb_beets += lb_temp;
break;
}
case 'c':
{
printf("Enter pounds of carrots: ");
scanf("%lf", &lb_temp);
lb_carrots += lb_temp;
break;
}
default:
{
printf("%c is not a valid choice.\n", ch);
}
}
printf("Enter a to buy artichokes, b for beets, ");
printf("c for carrots, q to quit: ");
}
cost_artichokes = price_artichokes * lb_artichokes;
cost_beets = price_beets * lb_beets;
cost_carrots = price_carrots * lb_carrots;
cost_total = cost_artichokes + cost_beets + cost_carrots;
lb_total = lb_artichokes + lb_beets + lb_carrots;
if (lb_total <= 0)
{
shipping = 0.0;
}
else if (lb_total < 5.0)
{
shipping = under5;
}
else if (lb_total < 20.0)
{
shipping = under20;
}
else
{
shipping = base20 + extralb * lb_total;
}
if (cost_total > 100.0)
{
discount = DISCOUNT_RATE * cost_total;
}
else
{
discount = 0.0;
}
final_total = cost_total + shipping - discount;
printf("Your order:\n");
printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2f\n",
lb_artichokes, price_artichokes, cost_artichokes);
printf("%.2f lbs of beets at $%.2f per pound: $%.2f\n",
lb_beets, price_beets, cost_beets);
printf("%.2f lbs of carrots at $%.2f per pound: $%.2f\n",
lb_carrots, price_carrots, cost_carrots);
printf("Total cost of vegetables: $%.2f\n", cost_total);
if (cost_total > 100)
{
printf("Volume discount: $%.2f\n", discount);
}
printf("Shipping: $%.2f\n", shipping);
printf("Total charges: $%.2f\n", final_total);
return 0;
}