c++入门2---while循环的使用

来源:互联网 发布:学服装设计软件 编辑:程序博客网 时间:2024/05/17 09:20

参考书《c++ primer 》第五版。

题目:p11页练习题

1.9

使用while循环将50到100的整数相加

#include <iostream>int main(){int i = 50,sum  = 0;while (i <= 100){sum += i;i++;}std::cout << "1+2+……+99+100 = " << sum << std::endl;system("pause");return 0;}
1.10

提示用户输入两个整数,打印出这两个数所指定的范围内的所有整数。

输入: 3 7

输出:3 4 5 6 7

输入:7 3

输出:7 6 4 3

#include <iostream>int main(){int start, end;std::cout << "请输入两个整数" << std::endl;std::cin >> start >> end;if (start < end){while (start <= end){std::cout << start << " ";start++;}std::cout << std::endl;}else{while (start>=end){std::cout << start << " ";start--;}std::cout << std::endl;}system("pause");return 0;}