重读《C primer plus》(七)

一、程序示例1-if语句

//colddays.c
#include<stdio.h>
int main()
{
		const int FREEZING = 0;
		float temperature;
		int cold_days = 0;
		int all_days = 0;

		printf("Enter the list of daily low temperatures.\n");
		printf("Use Celsius, and enter q to quit.\n");
		while (scanf("%f",&temperature) == 1)
		{
				all_days++;
				if(temperatures < FREEZING)
						cold_days++;
	    }
	    if(all_days != 0)
	    printf("%d days total: %.1f% were below freezing .\n",all_days,100.0*(float) cold_days/all_days);
	    if(all_days == 0)
	    		printf("No dats entered!\n");
	    return 0;
}

二、if else语句

1.简单介绍putchar()和getchar()

getchar()函数不带任何参数,它从输入队列中返回下一个字符。例如,ch = getchar();该语句效果和scanf(“%c”,&ch);语句作用效果一样。
putchar()函数打印它的参数。例如,下面的语句把之前赋给ch的值作为字符打印出来。
putchar(ch);该语句效果和printf(“%c”.ch);一样。

2.多重选择else if

3.多层嵌套的if语句

三、逻辑运算符

表1 3种逻辑运算符
逻辑运算符含义
&&

由于在C语言中的||运算符,与markdown语法有矛盾,故此不在表格中列出。

四、单词计数器程序

//wordcnt.c
#include<stdio.h>
#include<ctype.h> // 引入了isspace函数
#include<stdbool.h>// bool值的引入
#define STOP '|' // 表示在输入|时,程序停止运行
int main()
{
		char c;
		char prev;
		long n_chars = 0L;
		int n_lines = 0;
		int n_words = 0;
		int p_lines = 0;
		bool inword = false;

		printf("Enter text to be analyzed (| to terminnate):\n");
		prev = '\n';
		while((c = getchar()) != STOP)
		{
				n_chars++;
				if(c == '\n')
						n_lines++;
				if(!isspace(c) && !inword)
				{
						inword = true;
						n_words++;
			    }
			    if(isspace(c) && inword)
			    		inword = false;
			    prev = c;
		}
		if(prev != '\n')
			p_lines = 1;
		printf("characters = %ld,words = %d,lines = %d,",n_chars,n_words,n_lines);
		printf("partial lines = %d\n",p_lines);

	  return 0;
}

五、多重选择:switch和break

感悟:swit语句和if else相比感觉还是不够灵活,将一个学精比学的多而杂感觉要好得多。

六、goto语句

C语言中尽量不要使用goto语句,goto label和Java中的break以及coninue有点相似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值