1

10min快速回顾C++语法(三)

 2 years ago
source link: https://blog.51cto.com/u_15736437/5569278
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++的语法基础(三)

⭐写在前面的话:本系列文章旨在短时间内回顾C/C++语法中的重点与易错点,巩固算法竞赛与写题过程中常用的语法知识,精准地解决学过但有遗忘的情况,为算法刷题打下坚实的基础。

五、循环语句

5.1 while循环

可以简单理解为循环版的​​if​​语句。

  • if语句是判断一次,如果条件成立,则执行后面的语句;
  • while是每次判断,如果成立,则执行循环体中的语句,否则停止。括号内不能为空。

可以用循环求斐波那契数列的第n项。f(1) = 1, f(2) = 1, f(3) = 2, f(n) = f(n-1) + f(n-2)。

可以用变量或者数组的方法写。

#include <iostream>

using namespace std;

int main()
{
int n;
cin >> n;

int a = 1, b = 1, i = 1;
while (i < n)
{
int c = a + b;
a = b;
b = c;
i ++ ;
}
cout << a << endl;
return 0;
}

死循环:循环永久执行,无法结束。我们要避免写出死循环。

5.2 do while循环

​do while​​循环不常用。

do while语句与while语句非常相似。唯一的区别是,do while语句限制性循环体后检查条件。不管条件的值如何,我们都要至少执行一次循环

#include <iostream>

using namespace std;

int main()
{
int x = 1;
while (x < 1)
{
cout << "x!" << endl;
x ++ ;
}

int y = 1;
do
{
cout << "y!" << endl;
} while (y < 1);

return 0;
}
5.3 for循环

基本思想:把控制循环次数的变量从循环体中剥离。

for (init-statement ;condition; expression)
{
statement
}

​init-statement​​可以是声明语句、表达式、空语句,一般用来初始化循环变量; ​​condition​​是条件表达式,和while中的条件表达式作用一样;可以为空,空语句表示true​expression​​一般负责修改循环变量,可以为空。每次结束后都会执行。

5.4 多层循环
#include <iostream>

using namespace std;

int main()
{
for (int i = 0, k = 1; i < 10; i ++ )
{
for (int j = 0; j < 10; j ++, k ++ )
{
cout << k << ' ';
}
cout << endl;
}

return 0;
}

注意这里外层循环中定义的数可以在内层循环中使用

练习:打印1~100中的所有质数

#include <iostream>

using namespace std;

int main()
{
for (int i = 2; i <= 100; i ++ )
{
bool is_prime = true;
for (int j = 2; j < i; j ++ )
{
if (i % j == 0)
{
is_prime = false;
break;
}
}
if (is_prime) cout << i << endl;
}

return 0;
}

练习:输入一个n,打印n阶菱形。n是奇数。

#include <iostream>

using namespace std;

int main()
{
int n;
cin >> n;

int cx = n / 2, cy = n / 2;

for (int i = 0; i < n; i ++ )
{
for (int j = 0; j < n; j ++ )
if (abs(i - cx) + abs(j - cy) <= n / 2)
cout << '*';
else cout << ' ';
cout << endl;
}

return 0;
}

output

10min快速回顾C++语法(三)_跳转语句

此题可以采用曼哈顿距离简化。所有点距离中心的距离小于某一值,将其输出,剩余的输出为空格即可。*

六、跳转语句

6.1 break

可以提前从循环中退出,一般与if语句搭配。 例题:判断一个大于1的数是否是质数:

#include <iostream>

using namespace std;

int main()
{
int n;
cin >> n;

bool is_prime = true;
for (int i = 2; i < n; i ++ )
if (n % i == 0)
{
is_prime = false;
break;
}

if (is_prime) cout << "yes" << endl;
else cout << "no" << endl;

return 0;
}
6.2 continue

可以直接跳到当前循环体的结尾,也就是跳过本次循环。作用与if语句类似。

例题:求1~100中所有偶数的和。

#include <iostream>

using namespace std;

int main()
{
int sum = 0;

for (int i = 1; i <= 100; i ++ )
{
if (i % 2 == 1) continue;
sum += i;
}

cout << sum << endl;

return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK