《C Primer Plus》中文第六版 编程练习答案 第七章 C控制语句:分支和跳转

C Primer Plus 第7章 C控制语句:分支和跳转

关于continue和break的及i++情况说明

continue 返回到while循环 break 跳出while循环,执行下面语句
switch中无continue,while{switch() case}中break只是跳出switch循环(内层循环),while继续循环
for循环中,break执行for后面语句,不更新i++,而continue会对上轮i++更新;
再说一下关于 i++和 ++i 情况。
i++,递增完 i++本身值不改变 ,++i本身值+1
while(i++<n){} i先比较后再递增,递增是在()完了之后,立马递增,不等{}
而while(++i<n){} i先递增后比较

1.编写一个程序读取输入,读到#字符停止,然后报告读取的空格数、换行符数和所有其他字符的数量。

#include <stdio.h>
#define STOP '#'
#define SPACE ' ' 
int main(void)
{
   
    char c;
    char prev;
    int n_space=0;
    int n_lines=0;
    int n_others;
    printf("Enter the text(# to terminate):\n");
    while((c=getchar())!=STOP)
    {
   
    	if(c=='\n')
    	{
   
    		n_lines++;
		}
		else if(c==SPACE)//不用空白字符是因为其包括空格 、换页符、回车符等P156 
		{
   
			n_space++;
		}
		else{
   
			n_others++;
		}	 
	}
    printf("行数是%d\n 空格数是%d\n 其他符号是%d\n",n_lines,n_space,n_others);
    return 0;
}

2.编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的ASCII码(十进制)。一行打印8个字符。建议:使用字符计数和求模运算符(%)在每8个循环周期时打印一个换行符。

#include <stdio.h>
#define STOP '#'
int main(void)
{
   
    char c;
    int n_chars=0 ;
    printf("Enter the text(# to terminate):\n");
    while((c=getchar())!=STOP)
    {
   
    	if(n_chars++%8==0)
    	{
   	
    		printf("\n");
	    }
	    if(c=='\n') //对'\t'、'\n'、'\f'等有的转义序列需要说明 P45
	    {
   
	    	 printf("“\\n-%d”",c);
		}
	    else 
		{
   
		printf("“%c-%d”",c,c);
	    }
	}
    return 0;
}

3.编写一个程序,读取整数直到用户输入0。输入结束后,程序应报告用户输入的偶数(不包括0)个数、这些偶数的平均值、输入的奇数个数及其奇数的平均值。

#include <stdio.h>
int main(void)
{
   
    int num;
    int n_even=0,n_odd=0;
    float sumeven=0,sumodd=0;//此处注意类型转换 
    float mean_even, mean_odd;
    printf("Enter the number(0 to terminate):\n");
    while(scanf("%d", &num) == 1 && num != 0)
    {
   
        if(num%2==0)
    	{
   
		    n_even++;
		    sumeven+=num;
	    }
	    else
	    {
   
	    	n_odd++;
	    	sumodd+=num;
		}
	}
    mean_even=sumeven/n_even;
	mean_odd=sumodd/n_odd;
	printf("偶数个数是%d,偶数平均数是%f\n",n_even,mean_even);
	printf("奇数个数是%d,奇数平均数是%f\n",n_odd,mean_odd);
    return 0;
}

4.使用if else 语句编写一个程序读取输入,读到#停止。用感叹号替换句号,用两个感叹号替换原来的感叹号,最后报告进行了多少次替换。

#include <stdio.h>
#define STOP '#' 
int main(void)
{
   
    char c;
    int n=0;
    while((c=getchar())!=STOP)
    {
   
    	if(c=='.')
    	{
   
    		printf("!");
    		n++;
		}
		else if(c=='!')
		{
   
			printf("!!");
			n++;
		}
		else
        {
   
            printf("%c",c);
        }
	}
	printf("\n转换次数总数是%d",n);
    return 0;
}

5.使用switch重写练习4。

#include <stdio.h>
#define 
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值