五.C控制语句:循环

本文介绍了C语言中while循环的使用,包括带和不带花括号的区别,以及新引入的_Bool类型来表示真假值。此外,还展示了for循环在处理数组和计算平均值的应用,以及如何利用函数返回值进行循环控制。同时提到了程序跳转的关键字如break、continue和goto。
摘要由CSDN通过智能技术生成

1.while循环


#include<stdio.h>

int main(void)

{

long num;

long sum = 0L;//初始化sum为0

int status;

printf("Please enter an integer to be summed");

printf("(q to quit): ");

status = scanf("%ld", &num);

while (status == 1)

{

sum += num;

printf("Please enter next integer (q to quit): ");

status = scanf("%ld", &num);

}

printf("Those integers sum to %ld.\n", sum);

return 0;

}

如果加了花括号,while循环的范围包含花括号内的所有代码,如果没使用花括号,则while循环仅仅包含了到下一个分号

新的_Bool类型


在C语言中,一直使用int类型的变量表示真假值。C99专门对这种类型变量新增了_Bool类型。

如果把其他非零数值赋给_Bool类型的变量,该变量会被设置为1,这反映了C把所有的非零值都视为真。

,的特性


a = (249, 500);

这个赋值语句中,a的值为逗号右侧表达式的值,即为500.

for循环中使用数组:


#include<stdio.h>

#define SIZE 10

#define PAR 72

int main(void)

{

int index, score[SIZE];

int sum = 0;

float average;

printf("Enter %d golf scores:\n", SIZE);

for (index = 0; index < SIZE; index++)

{

scanf("%d", &score[index]);

}

printf("The score read in are as follows:\n");

for ( index = 0; index < SIZE; index++)

{

printf("%5d", score[index]);

}

printf("\n");

for (index = 0; index < SIZE; index++)

{

sum += score[index];

}

average = (float)sum / SIZE;

printf("Sum of scores = %d, average = %.2f\n", sum, average);

printf("That is a handicap of %.0f.\n", average - PAR);

return 0;

}

使用函数返回值的循环示例:


#include<stdio.h>

double power(double n, int p);

int main(void)

{

double x;

double xpow;

int exp;

printf("Enter a number and the positive integer power");

printf("to which\nthe number will be raised. Enter q");

printf("to quit.\n");

while (scanf("%lf%d", &x, &exp) == 2) {//这里scanf()函数的值如果使用==运算符那么会得到接收到的数目

xpow = power(x, exp);

printf("%.3g to the power %d is %0.5g\n", x, exp, xpow);

printf("Enter next pair of numbers or q to quit.\n");

}

printf("Hope you enjoy this power trip -- bye!\n");

return 0;

}

double power(double n, int p)

{

double pow = 1;

int i;

for (i = 0; i <= p; i++) {

pow *= n;

}

return pow;

}

如果在程序中包含了头文件 stdbool.h ,那么便可以用bool代替_Bool 类型,用 true 和 false 代替 1 和 0

备选拼写:iso646.h 头文件:可以用 and 代替 && 用 or 代替 || 用 not 代替 !

程序跳转


关键字:break, continue, goto

主要讲讲goto语句:使程序控制跳转至相应标签语句。冒号用于分隔标签和标签语句。标签名遵循变量命名规则。标签语句可以出现在goto前面或后面

示例:

goto label ;

.

.

.

label : statement

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Benaso

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值