文章目录
一、程序示例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语句
三、逻辑运算符
逻辑运算符 | 含义 |
---|---|
&& | 与 |
! | 非 |
由于在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有点相似。