#1.1节练习
练习1.1:查阅你使用的编译器文档,确定它所使用的文件命名约定。编译并且运行第2页的main程序。
练习1.2 改写程序,让他返回-1
#1.2节练习
练习1.3 hello, world 程序
#include <iostream>
int main()
{
std::cout << "Hello, World " << std::endl;
return 0;
}
练习1.4 乘法程序
#include <iostream>
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 * v2 << std::endl;
return 0;
}
1.5 输出流分解
#include <iostream>
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of ";
std::cout << v1;
std::cout << " and ";
std::cout << v2;
std::cout << " is ";
std::cout << v1 + v2;
std::cout << std::endl;
return 0;
}
1.6 下面程序是否合法
std::cout << "The sum of " << v1 ;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
不合法,后面两句输出运算符<<左边没有ostream对象,修正如下:
std::cout << "The sum of " << v1 ;
std::cout<< " and " << v2;
std::cout << " is " << v1 + v2 << std::endl;
#1.4节练习
1.9 计算50到100的和
#include <iostream>
/*
* sum the numbers from50 to 100
*/
int main()
{
int sum = 0, val = 50;
// keep executing the while as long as val is less than or equal to 100
while (val <= 100) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
} std::cout << "Sum of 50 to 100 inclusive is "
<<sum << std::endl;
return 0;
}
1.10 打印10到0
#include <iostream>
/*
* prints the numbers from ten down to zero
*/
int main()
{
int i = 10;
while (i >= 0) {
std::cout << "The number is: "
<< i << std::endl;
--i;
}
return 0;
}
1.11 输入两个数字,打印范围内的数字
#include <iostream>
/*
* Print each number in the range specified by those two integers
*/
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
if (v2> v1)
{
int i = v1;
while (i <= v2) {
std::cout << i << ", ";
++i;
}
std::cout << std::endl;
}
else if (v2 < v1)
{
int i = v2;
while (i <= v1) {
std::cout << i << ", ";
++i;
}
std::cout << std::endl;
}
else
std::cout << v1 << std::endl;
return 0;
}