目录
for循环
比较常用的循环,注意,C标准不一样,存在循环体判断变量定义的问题,详情请看我的C语言错误总结:https://blog.csdn.net/weixin_46097842/article/details/116187455
for循环的第一个参数是变量,第二个参数是判断表达式,第三个是变量操作调整
#include <stdio.h>
int main() {
int price = 100;
for (price; price >= 1 ; --price) {
printf("降价了,现在价格是: %d\n", price);
if ( 1 == price) {
printf("不能再低了,再低就是免费送了.......");
}
}
return 0;
}
while 循环
#include <stdio.h>
int main() {
int price = 100;
int i;
// for (i = 0; i < 100; ++i) {
// printf("降价了,现在价格是: %d\n", price);
// price--;
// }
// for (price; price >= 1; --price) {
// printf("降价了,现在价格是: %d\n", price);
// if (1 == price) {
// printf("不能再低了,再低就是免费送了.......");
// }
// }
while (price >= 1) {
printf("降价了,现在价格是: %d\n", price);
if (1 == price) {
printf("不能再低了,再低就是免费送了.......");
}
price--;
}
return 0;
}
运行效果
do while 循环
先上代码和运行结果
#include <stdio.h>
int main() {
int price = 100;
int i;
// for (i = 0; i < 100; ++i) {
// printf("降价了,现在价格是: %d\n", price);
// price--;
// }
// for (price; price >= 1; --price) {
// printf("降价了,现在价格是: %d\n", price);
// if (1 == price) {
// printf("不能再低了,再低就是免费送了.......");
// }
// }
do {
printf("这个是必然执行的\n");
price--;
}
while (price %2 == 0);
printf("程序要结束了...");
// {
// printf("降价了,现在价格是: %d\n", price);
// if (1 == price) {
// printf("不能再低了,再低就是免费送了.......");
// }
// price--;
// }
return 0;
}
do while结构代表,执行do代码体的代码,然后走while判断,当满足while条件的时候再执行do代码体的代码,也就是说,do while循环会至少执行一次循环的内容
死循环
所谓死循环,就是说这个判断永远为true, 永远执行循环的内容
for的死循环
#include <stdio.h>
int main() {
for(;;) {
printf("循环的内容~ \n");
}
return 0;
}
while的死循环
#include <stdio.h>
int main() {
while(1) {
printf("循环的内容~ \n");
}
return 0;
}
do while与while一样的道理
continue和break
continue代表跳过本次循环,下次循环还是会执行,break代表终止所在的循环 --注意,无论是while还是for循环,都可以使用continue和break
先说continue,上代码
#include <stdio.h>
int main() {
int price = 20;
while (price >= 0) {
price--;
if (price %2 != 0) {
continue;
}
printf("这是一个偶数 %d\n", price);
}
return 0;
}
猜猜这个代码是什么意思? 对!就是输出偶数
而我们试试break
#include <stdio.h>
int main() {
int price = 20;
while (price >= 0) {
price--;
printf("现在的价格是:%d\n", price);
if (price %2 == 0) {
break;
}
}
return 0;
}
猜猜看这个程序作用是什么~ 猜猜看运行结果?
哦呦,遇到偶数程序就跳出循环结束了