c++ primer学习日记 - -第1章习题

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值