1、三种循环方式--->
for、while、do while2、函数
fabs()3、编写有返回值的函数
三种循环方式
while
示例代码:
变式:
注意:
每次循环都被称为一次迭代
循环终止条件:
注意:
_Bool类型
注意:
bool 不是 c语言的关键字, 但是c99标准和c++把bool当作关键字
For
/**
* @Author: Lucifer
* @Date: 4/16/2023, 4:40:59 PM
* @LastEditors: Lucifer
* @LastEditTime: 4/16/2023, 4:40:59 PM
* Description: A case about for
* Copyright: Copyright (©)}) 2023 Your Name. All rights reserved.
*/
字符代替数字作为测试条件和初始值:
省略循环表达式写法:
/**
* @Author: Lucifer
* @Date: 4/16/2023, 5:26:45 PM
* @LastEditors: Lucifer
* @LastEditTime: 4/16/2023, 5:26:45 PM
* Description: for循环当中省略表达式的写法
* Copyright: Copyright (©)}) 2023 Your Name. All rights reserved.
*/
逗号运算符运用在for循环中表达多种用法:
/** * @Author: Lucifer * @Date: 4/16/2023, 5:37:23 PM * @LastEditors: Lucifer * @LastEditTime: 4/16/2023, 5:37:23 PM * Description: ,运算符,在一个for循环中,每个条件表达式可以用,来表达多种条件 * Copyright: Copyright (©)}) 2023 Your Name. All rights reserved. */ # include<stdio.h>int main(void)
{
const int FIRST_OZ = 46;
const int NEXT_OZ = 20;
int ounces, cost;printf(" ounces cost\n"); for (ounces = 1, cost = FIRST_OZ; ounces <= 16; ounces++, cost += NEXT_OZ) { printf("%5d $%4.2f\n", ounces, cost / 100.0); } getchar(); return 0;}
示例代码2:
/** * @Author: Lucifer * @Date: 4/16/2023, 7:41:35 PM * @LastEditors: Lucifer * @LastEditTime: 4/16/2023, 7:41:35 PM * Description: ZenO悖论 * Copyright: Copyright (©)}) 2023 Your Name. All rights reserved. */ # include<stdio.h>int main(void)
{
int t_ct; // 项计数
double time, power_of_2;
int limit;printf("输入你想射几米:"); scanf("%d", &limit); // 箭永远只会行进一半的路程 for (time = 0, power_of_2 = 1, t_ct = 1; t_ct <= limit; t_ct++, power_of_2 *= 2.0) { time += 1.0 / power_of_2; printf("time = %f, 当terms = %d \n", time, t_ct); } getchar(); getchar(); return 0;}
do...while
示例代码:
/** * @Author: Lucifer * @Date: 4/16/2023, 7:47:13 PM * @LastEditors: Lucifer * @LastEditTime: 4/16/2023, 7:47:13 PM * Description: 猜数字游戏 * Copyright: Copyright (©)}) 2023 Your Name. All rights reserved. */ # include<stdio.h>int main(void)
{
const int secret_code = 13;
int code_entered;do { printf("有一个内置的数,在10到20之间,猜猜是几?:\n"); printf("请输入你猜的数:\n"); scanf("%d", &code_entered); getchar(); } while (code_entered != secret_code); printf("猜对了,游戏结束!"); getchar(); return 0;}