Accelerated C++ 第0章有感及习题答案

本文详细介绍了C++的基本程序结构,从`#include <iostream>`开始,讲解了`main()`函数、`cout`输出、返回值以及常用标识符。通过实例展示了如何输出Hello, world! 和字符串处理,以及正确使用命名空间。
摘要由CSDN通过智能技术生成
#include <iostream>
int main()
{
    std::cout << "hello world" << std::endl;
    return 0;
}

1.注意 cout 不属于语言核心 而是标准库(stadrand template library )的一部分 所以在使用前必须引入相关的头文件 即用 #include 标准头文件iostream定义了cout 所以<> 里面是 iostream

2.int main 中的int 代表返回类型  表示必须要返回一个int类型的数  0 标志执行成功 但是 main 函数比较特殊 即使不写返回值  也会默认返回 一个 0 但即便如此 我们也要 养成写返回值的习惯

3.std::cout << "hello world" << std::endl  这是一个表达式  他会有一个返回值  但是却也有副作用          

即   把hello world 输出到屏幕上 当我们给这个表达式加上分号时 它成了一条语句 此时它便没有返回值  但那没有关系 因为我们只是想要他的副作用而已

答案
0-0  编译并运行 Hello,world!程序。

#include <iostream>
using namespace std;
int main() 
{
    cout << "hello world" << endl;
    return 0;
}


0-1  下面的表达式是做什么的?  3 + 4?


结果为7 计算 3 和 4 的 和 并没有副作用产生


0-2  

编写一个程序,使它在运行时输出。

This (“) is a quote , and this (\) is a backlash.

#include <iostream>
using namespace std;
int main() 
{
    cout << "this (\") is a quote , and this (\\) is a backlash" << endl;
    return 0;
}


0-3  字符串直接量“\t”代表一个水平制表符,不同的C++实现以不同的形式显示制表符,在你的实现中试验一下,看它是怎么处理制表符的。

#include <iostream>
using namespace std;
int main()
{
	cout << "这是个制表符例子,占几个\t\t字节?" << endl;  //第一个占一个英文字符 第二个占四个汉字  运行在vs2010
	cout << "这是个制表符例子,这是个abcd比例子,请注意观察。" << endl;
	return 0;
}


0-4  将hello world 程序作为结果输出

#include <iostream>
using namespace std;
int main() 
{
    cout << "#include <iostream>" << endl;
    cout << "using namespace std;" << endl;
    cout << "int main()" << endl;
    cout << "{" << endl;
    cout << "\tcout << \"Hello world!\" << endl;" << endl;
    cout << "\treturn 0;" << endl;
    cout << "}" << endl;
    return 0;
}


0-5    

下面的程序是一个有效的程序吗?说出理由。

#include <iostream>

Int main()   std::cout << “Hello World!” << std::endl;

该程序不是一个有效的程序,因为 哪怕是一条语句,函数体都必须用一对花括号{} 括住。
0-6

下面的程序是一个有效的程序吗?说出理由。

#include <iostream>

Int main()

{

{{{{{  std::cout << “Hello World!” << std::endl;  }}}}}

}

是 只不过是作用域的层层嵌套而已 并不影响 程序的合理性
0-7

那下面这个程序呢?

#include <iostream>

Int main()

{

/*这是一个注释,因为我们使用了/*和*/来作为它的定界符,

所以它占据了几行的范围*/

Std::cout << “Does this work?” << std::endl;

Return 0;

}

不是 第一行的/* 和第一行的 */已经构成了一条注释语句,所以*/之后的内容和第二行的内容不会被当做注释的内容,会出现编译失败的警告。
0-8

  ..............这个呢?

#include <iostream>

Int main()

{

//这是一个注释,它占据了几行的范围

//在这里,我们使用了//而不是/*

//和*/来为注释定界

Std::cout << “Does this work?” << std::endl;

Return 0;

}

是 注释并不会影响程序的合理性   //注释虽然不具有自由风格 但是三行注释都加了 // 所以没关系
0-9  最短的有效程序是什么?

int main()
{
    return 0;
}

0-10   重写Hello,world!程序,让程序中每一个允许出现空白的地方都换行。

#include <iostream>
using 
	namespace
	Std
;
int 
	Main
()
{
	cout 
		<< 
		"Hello world!" 
		<< 
		Endl
;
	return 
		0
;
}


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值