您的位置:首页 > 编程语言 > C语言/C++

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

2017-01-12 16:07 766 查看

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
时,
condition
TRUE


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
系统使用同时键入
ctrl
z
作为文件结束符;
Unix
系统下则使用
control-d


遇到无效输入。如上述
code
我们输入非整数值。

注意:上述
code
在使用非整数负数进行结束时,该负数会被计入
cout
变量。


Postscript:

关于本章
1.5
1.6
两个关于
的简介,就不再继续展开了,在以后的章节中具体学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++
相关文章推荐