第一章 C++ 我来了——1.3 关于注释 & 1.4 While, For and If

时间:2022-12-13 15:31:52

1.3 注释


注释嘛咱就不多说了,照着葫芦画瓢吧!喏,葫芦就在下面:

#include <iostream>
/* I am block comments
* The soft engineers like to employ the "*" as the head of the line to indicate
* this line is still a part of the block comments
*/

int main()
{
//I am single line comments, I can only protect the content in this line
return 0;
}

1.4 While, For and If


1.4.1 While

while (condition) while_body-statement;
#include <iostream>

int main ()
{
int sum = 0, val = 1;

while (val <= 10)
{
sum += val;
++val;
}

std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
return 0;
}

Tips:

  • 在使用控制结构进行迭代时,总会需要对condition进行判断。如果condition为真时,则执行while_body_statement。请注意,表达式求值不为0时,conditionTRUE

1.4.2 For


#include <iostream>

int main ()
{
int sum = 0;

for (int val = 0; val <= 10; ++val)
sum += val;

std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
return 0;
}

1.4.3 If


#include <iostream>
//Calculate the sum of the numbers between v1 and v2
int main ()
{
std::cout << "Enter two numbers: " <<std::endl;
int v1, v2;
std::cin >> v1 >> v2;

int lower, upper;
if(v1 <= v2){
lower = v1;
upper = v2;
}
else{
lower = v2;
upper = v1;
}

int sum = 0;
for (int i = lower; i <= upper; ++i){
sum += i;
}
std::cout << sum <<std::endl;

return 0;
}

1.4.4 读入未知数目的输入


OK,终于有点新东西了,看,那个人好像条狗啊!

#include <iostream>

int main ()
{
int cout = 0, value;

while(std::cin >> value){
if(value < 0){
++cout;
}
}
std::cout << cout <<std::endl;

return 0;
}

Tips:

在使用std::cin >> value进行判断时,有两种情况可以终止循环。

  • 遇到文件结束符(end-of-file)。不同的操作系统使用不同的值作为文件结束符,Windows系统使用同时键入ctrlz作为文件结束符;Unix系统下则使用control-d
  • 遇到无效输入。如上述code我们输入非整数值。
  • 注意:上述code在使用非整数负数进行结束时,该负数会被计入cout变量。

Postscript:

关于本章1.51.6两个关于的简介,就不再继续展开了,在以后的章节中具体学习。