#include<iostream>//预处理命令usingnamespace std;//命名空间intmain(){
cout <<"Hello!"<< endl;//输出
cout <<"Welcome to C++!"<< endl;return0;}
输入一个年份,判断是否是闰年
#include<iostream>usingnamespace std;intmain(){
int year;bool isLeapYear;
cout <<"输入一个年份:"<< endl;
cin >> year;
isLeapYear =((year %4==0&& year %100!=0)||(year %400==0));if(isLeapYear)
cout << year <<" is a leap year"<< endl;else{
cout << year <<" is not a leap year"<< endl;}return0;}
比较两个数的大小
#include<iostream>usingnamespace std;intmain(){
int x, y;
cout <<"Enter x and y:";
cin >> x >> y;if(x != y)if(x > y)
cout <<"x>y"<< endl;else{
cout <<"x<y"<< endl;}else{
cout <<"x=y"<< endl;}return0;}
输入一个0~6的整数,转换成星期输出
#include<iostream>usingnamespace std;intmain(){
int day;
cin >> day;switch(day){
case0:
cout <<"Sunday"<< endl;break;case1:
cout <<"Monday"<< endl;break;case2:
cout <<"Tuesday"<< endl;break;case3:
cout <<"Wednesday"<< endl;break;case4:
cout <<"Thursday"<< endl;break;case5:
cout <<"Friday"<< endl;break;case6:
cout <<"Saturday"<< endl;break;default:
cout <<"Day out of range Sunday...Saturday"<< endl;break;}return0;}
求1~10的之和
#include<iostream>usingnamespace std;intmain(){
int i =1,sum =0;while(i <=10){
sum += i;
i++;}
cout <<"sum="<< sum << endl;return0;}
输入一个整数,将各位数字反转后输出
#include<iostream>usingnamespace std;intmain(){
int n, right_digit, newnum =0;
cout <<"Enter the number:";
cin >> n;
cout <<"The number in reverse order is ";do{
right_digit = n %10;
cout << right_digit;
n /=10;}while(n !=0);
cout << endl;return0;}
用do…while语句编程,求自然数1~10之和
#include<iostream>usingnamespace std;intmain(){
int i =1, sum =0;do{
sum += i;
i++;}while(i <10);
cout <<"sum="<< sum << endl;return0;}
输入一个整数,求出它的所有因子
#include<iostream>usingnamespace std;intmain(){
int n;
cout <<"Enter a postive integer:";
cin >> n;
cout <<"Number "<< n <<" Factors ";for(int k =1; k <= n; k++){
if(n % k ==0){
cout << k <<" ";}}
cout << endl;return0;}
编写输出图案
#include<iostream>usingnamespace std;intmain(){
constint N =4;for(int i =1; i <= N; i++){
for(int j =1; j <=30; j++){
cout <<' ';}for(int j =1; j <=8-2* i; j++){
cout <<' ';}for(int j =1; j <=2* i -1; j++){
cout <<'*';}
cout << endl;}for(int i =1; i <= N -1; i++){
for(