《C语言大学教程(第八版)》第四章 课后习题 4.35 参考答案

前言
  一开始,遇到这道题目,一头雾水,后来几经查阅,获得启发。
在这里插入图片描述

思考
  for语句头里面的判断条件可以设置多个部分。
解决
  先看图4.11程序中的代码,如下所示:

#include <stdio.h>

int main (void)
{
	unsigned int x; // declared so it can be used after loop
	// loop 10 times
	for (x = 1; x <= 100; ++x)
	{
		// if x is 5, terminate loop
		if (x == 5)
		{
			break; // break loop only if x is 5
		}
		
		printf("%u", x);
	}

	printf("\nBroke out of loop at x == %u\n", x);
}

  通过使用等价的结构,去掉break;语句,如下所示:

#include <stdio.h>
int main (void)
{
    unsigned int x; // declared here so it can be used after loop
    int y;

    y = 1;

    // loop 10 times
    for (x = 0; x <= 10 && y == 1; ++x)
    {
        if (x == 4)
        {
            y = 0;
        }
        
        printf("%u", x);
        
    }

    printf("\nBroke out of loop at x == %u\n", x);
}

  注意,for语句头里面的判断条件设置为两部分。代码写完后,运行验证是否正确,如下图所示:
在这里插入图片描述
  结果一致。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值