Chapter One Code Block
【note】
The analysis is in the code comments
1. while code
1.1 Use a while loop to add 50 to 100
//用while循环将50加到100(整数相加)
#include<iostream>
int main()
{
int sum = 0;
int v1 = 50;
while (v1 <= 100)
{
sum = sum + v1;
v1++;
}
std::cout << "The sum of 50 to 100 is " << sum << "\n";
return 0;
}
1.2 The loop outputs 10 to 0 in decreasing order
//循环按照递减输出10到0
#include<iostream>
int main()
{
int v1 = 10;
while (v1 >= 0)
{
std::cout << v1 << "\n";
v1--;
}
return 0;
}
1.3 The user enters two numbers, and then outputs the sum of the numbers in the range
//用户输入俩个数字,然后输出范围内的数字之和
#include<iostream>
int main()
{
int v1, v2;
int sum = 0;
std::cout << "请输入v1和v2(v1 > v2)" << "\n";
std::cin >> v1 >> v2;
while (v2 <= v1)
{
sum = sum + v2;
v2++;
}
std::cout << "范围之和为:" << sum << "\n";
return 0;
}
2. for code
2.1 Use a for loop to output 1 to 10, and output the accumulated value
//用for循环输出1到10
#include<iostream>
int main()
{
int sum = 0;
for (int v1 = 1; v1 <= 10; ++v1)
{
std::cout << v1 << "\n";
sum = sum + v1;
}
std::cout << "The sum of 1 to 10 is " << sum << "\n";
return 0;
}
In for, you can directly assign values, that is, int v1 = 1 (different from C)
3.if code
3.1 Enter numbers continuously and record the number of times (if and while)
Unresolved bugs
If you do not enter a value different from the previous input, it will cause the program to be wrong
//连续输入数字,记录次数
//bug:如果没有输入一个与之前输入的不同值,就会导致程序有误。
#include<iostream>
int main()
{
int v1 = 0, v2 = 0;
if (std::cin >> v1)
{
int sum = 1;//初始值
do {
std::cin >> v2;
if (v1 == v2) {
sum++;//输入相同则加一运算
}
else {
//否则输出v1
std::cout << v1 << "出现过" << sum << "次" << std::endl;
v1 = v2;//将v2的值存储于v1中,与后输入的值比较
sum = 1;//再次初始化
}
} while (v2 != '\n');
//输出最后一次的值
std::cout << v1 << "出现过" << sum << "次" << std::endl;
}
return 0;
}
4. The difference between i++ and ++i
//++与--比较
#include<iostream>
int main()
{
int sum = 0;
int x, y;
//先x不变,后sum相加(++在后面)
x = sum++;
std::cout << x; //x = 0
std::cout << sum; //sum = 1
//y与sum都同时相加(此时sum=1)
y = ++sum;
std::cout << y; //y = 2
std::cout << sum; //sum = 2
return 0;
}