C++ 实例

36 阅读13分钟

使用 C++ 输出字符串 "Hello, World!",只是一个简单的入门实例,需要使用 main( ) 函数及标准输出 cout

实例

#include <iostream> using namespace std; 
int main() { 
    cout << "Hello, World!"; 
    return 0; 
}
    

使用 C++ 获取用户的输入,并输出到屏幕:

实例

#include <iostream> using namespace std; 
int main() { 
   int number; 
   cout << "输入一个整数: "; 
   cin >> number; 
   cout << "输入的数字为: " << number; 
   return 0; 
}

以上程序执行输出结果为:

输入一个整数: 12
输入的数字为: 12

使用 C++ 输出,并对多个输出内容进行换行,使用 \n 或 endl:

实例 - \n 换行

#include <iostream> using namespace std; 
int main() { 
    cout << "Runoob \n"; 
    cout << "Google \n"; 
    cout << "Taobao"; 
    return 0; 
 }

实例 - endl 换行

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

以上程序执行输出结果为:

Runoob 
Google 
Taobao

使用 C++ 获取用户的输入两个数字,并将两个数字相加,然后输出到屏幕:

实例

#include <iostream> using namespace std; 
int main() { 
int firstNumber, secondNumber, sumOfTwoNumbers; 
cout << "输入两个整数: "; 
cin >> firstNumber >> secondNumber; 
// 相加 
sumOfTwoNumbers = firstNumber + secondNumber; 
// 输出 
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers; 
return 0; 

}

以上程序执行输出结果为:

输入两个整数: 
4
5
4 + 5 = 9

以下实例展示了不同类型变量的创建方法:

实例

#include <iostream> 
#include <string> using namespace std; 
int main () { 
// 创建变量 
int myNum = 5; 
// 整型 
float myFloatNum = 5.99; 
// 单精度浮点型 
double myDoubleNum = 9.98; 
// 双精度浮点型
char myLetter = 'D';
// 字符型 
bool myBoolean = true;
// 布尔型 
string myString = "Runoob"; 
// 字符串 // 输出变量 
cout << "int: " << myNum << "\n"; 
cout << "float: " << myFloatNum << "\n"; 
cout << "double: " << myDoubleNum << "\n"; 
cout << "char: " << myLetter << "\n"; 
cout << "bool: " << myBoolean << "\n"; 
cout << "string: " << myString << "\n"; 
return 0; 
}

以上程序执行输出结果为:

int: 5
float: 5.99
double: 9.98
char: D
bool: 1
string: Runoob

使用 C++ 获取用户的输入两个数字,并将两个数字相除,然后将商和余数输出到屏幕:

实例

#include <iostream> using namespace std; 
int main() { 
int divisor, dividend, quotient, remainder; 
cout << "输入被除数: "; 
cin >> dividend; 
cout << "输入除数: "; 
cin >> divisor; 
quotient = dividend / divisor; 
remainder = dividend % divisor; 
cout << "商 = " << quotient << endl; 
cout << "余数 = " << remainder; 
return 0; 
}

以上程序执行输出结果为:

输入被除数: 13
输入除数: 4
商 = 3
余数 = 1

使用 C++ sizeof 运算符来计算 int, float, double 和 char 变量占用的空间大小。

sizeof 运算符语法格式:

sizeof(dataType);

注意: 不同系统计算结果可能不一样。

实例

#include <iostream> using namespace std; int main() { cout << "char: " << sizeof(char) << " 字节" << endl; cout << "int: " << sizeof(int) << " 字节" << endl; cout << "float: " << sizeof(float) << " 字节" << endl; cout << "double: " << sizeof(double) << " 字节" << endl; return 0; }

以上程序执行输出结果为:

char: 1 字节
int: 4 字节
float: 4 字节
double: 8 字节

以下我们使用两种方法来交换两个变量:使用临时变量与不使用临时变量。

实例 - 使用临时变量

#include <iostream> using namespace std; 
int main() { 
     int a = 5, b = 10, temp; 
     cout << "交换之前:" << endl; 
     cout << "a = " << a << ", b = " << b << endl; 
     temp = a; a = b; b = temp; 
     cout << "\n交换之后:" << endl; 
     cout << "a = " << a << ", b = " << b << endl; 
     return 0; }

以上程序执行输出结果为:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5

实例 - 不使用临时变量

#include <iostream> 
#include <iostream> using namespace std; 
int main() { 
     int a = 5, b = 10; 
     cout << "交换之前:" << endl; 
     cout << "a = " << a << ", b = " << b << endl; 
     a = a + b; 
     b = a - b; 
     a = a - b; 
     cout << "\n交换之后:" << endl; 
     cout << "a = " << a << ", b = " << b << endl; 
     return 0; 
 }

以上程序执行输出结果为:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5

以下我们使用 % 来判断一个数是奇数还是偶数,原理是,将这个数除于 2 如果余数为 0 为偶数,否则为奇数。

实例 - 使用 if...else

#include <iostream> using namespace std; 
int main() { 
int n; cout << "输入一个整数: "; 
cin >> n; 
if ( n % 2 == 0) cout << n << " 为偶数。"; 
else cout << n << " 为奇数。";
return 0; }

以上程序执行输出结果为:

输入一个整数: 5
5 为奇数。

实例 - 使用三元运算符

#include <iostream> using namespace std; 
int main() { 
    int n; cout << "输入一个整数: ";
    cin >> n; 
    (n % 2 == 0) ? cout << n << " 为偶数。" : cout << n << " 为奇数。";
    return 0; }

以上程序执行输出结果为:

输入一个整数: 5
5 为奇数。

英语有 26 个字母,元音只包括 a、e、i、o、u 这五个字母,其余的都为辅音。y是半元音、半辅音字母,但在英语中都把他当作辅音。

实例 1

#include<iostream> using namespace std; 
int main() { 
    char c; 
    bool ischar; 
    int isLowercaseVowel,isUppercaseVowel; 
    cout<<"输入一个字母:"; 
    cin>>c; 
    ischar=((c>='a'&&c<='z')||(c>='A'&&c<='Z')); 
    if(ischar) { 
        // 小写字母元音 
        isLowercaseVowel=(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'); 
        // 大写字母元音 
        isUppercaseVowel=(c=='A'||c=='E'||c=='I'||c=='O'||c=='U'); 
        // if 语句判断 
        if(isLowercaseVowel||isUppercaseVowel) 
          cout<<c<<" 是元音"; else cout<<c<<" 是辅音";
    } else { cout<<"输入的不是字母。"; } 
    return 0; 
    }

以上程序执行输出结果为:

输入一个字母: G
G 是辅音

实例 2

#include <iostream>  
using namespace std;  
  
bool isVowel(char letter) {  
    // 将字母转换为小写  
    letter = tolower(letter);  
  
    // 判断字母是否为元音  
    if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {  
        return true;  
    } else {  
        return false;  
    }  
}  
  
int main() {  
    char letter;  
    cout << "请输入一个字母: ";  
    cin >> letter;  
  
    if (isVowel(letter)) {  
        cout << letter << " 是元音字母。" << endl;  
    } else {  
        cout << letter << " 是辅音字母。" << endl;  
    }  
  
    return 0;  
}  

以上代码中,我们定义了一个函数 isVowel,它接受一个字母作为参数并返回一个布尔值。在函数中,我们将字母转换为小写字母,并使用条件语句判断它是否为元音。如果字母是元音,函数返回 true,否则返回 false。在主函数中,我们接受用户输入的字母,并调用 isVowel 函数进行判断,然后输出相应的结果。

通过屏幕我们输入三个数字,并找出最大的数。

实例 - 使用 if

#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if(n1 >= n2 && n1 >= n3) { cout << "最大数为: " << n1; } if(n2 >= n1 && n2 >= n3) { cout << "最大数为: " << n2; } if(n3 >= n1 && n3 >= n2) { cout << "最大数为: " << n3; } return 0; }

以上程序执行输出结果为:

请输入三个数: 2.3
8.3
-4.2
最大数为: 8.3

实例 - 使用 if...else


#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if((n1 >= n2) && (n1 >= n3)) cout << "最大数为: " << n1; else if ((n2 >= n1) && (n2 >= n3)) cout << "最大数为: " << n2; else cout << "最大数为: " << n3; return 0; }

以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3

实例 - 使用内嵌的 if...else


#include <iostream> using namespace std; int main() { float n1, n2, n3; cout << "请输入三个数: "; cin >> n1 >> n2 >> n3; if (n1 >= n2) { if (n1 >= n3) cout << "最大数为: " << n1; else cout << "最大数为: " << n3; } else { if (n2 >= n3) cout << "最大数为: " << n2; else cout << "最大数为: " << n3; } return 0; }

以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3

二次方程 ax2+bx+c = 0 (其中a≠0),a 是二次项系数,bx 叫作一次项,b是一次项系数;c叫作常数项。

image.png

实例


#include <iostream> #include <cmath> using namespace std; int main() { float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; cout << "输入 a, b 和 c: "; cin >> a >> b >> c; discriminant = b*b - 4*a*c; if (discriminant > 0) { x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a); cout << "Roots are real and different." << endl; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } else if (discriminant == 0) { cout << "实根相同:" << endl; x1 = (-b + sqrt(discriminant)) / (2*a); cout << "x1 = x2 =" << x1 << endl; } else { realPart = -b/(2*a); imaginaryPart =sqrt(-discriminant)/(2*a); cout << "实根不同:" << endl; cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl; cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl; } return 0; }

以上程序执行输出结果为:

输入 a, b 和 c: 4
5
1
实根不同:
x1 = -0.25
x2 = -1

计算 1+2+3+....+n 的和。

实例


#include <iostream> using namespace std; int main() { int n, sum = 0; cout << "输入一个正整数: "; cin >> n; for (int i = 1; i <= n; ++i) { sum += i; } cout << "Sum = " << sum; return 0; }

以上程序执行输出结果为:

输入一个正整数: 50
Sum = 1275

用户输入年份,判断该年份是否为闰年。

实例


#include <iostream> using namespace std; int main() { int year; cout << "输入年份: "; cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { // // 这里如果被 400 整除是闰年 if (year % 400 == 0) cout << year << " 是闰年"; else cout << year << " 不是闰年"; } else cout << year << " 是闰年"; } else cout << year << " 不是闰年"; return 0; }

以上程序执行输出结果为:

输入年份: 1990
1990 不是闰年

一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。

实例


#include <iostream> using namespace std; int main() { unsigned int n; unsigned long long factorial = 1; cout << "输入一个整数: "; cin >> n; for(int i = 1; i <=n; ++i) { factorial *= i; } cout << n << " 的阶乘为:"<< " = " << factorial; return 0; }

以上程序执行输出结果为:

输入一个整数: 12
12 的阶乘为: = 479001600

创建各类三角形图案。

实例


#include <iostream> using namespace std; int main() { int rows; cout << "输入行数: "; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { cout << "* "; } cout << "\n"; } return 0; }

以上程序执行输出结果为:

*
* *
* * *
* * * *
* * * * *

实例


#include <iostream> using namespace std; int main() { int rows; cout << "输入行数: "; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { cout << j << " "; } cout << "\n"; } return 0; }

以上程序执行输出结果为:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

实例


#include <iostream> using namespace std; int main() { char input, alphabet = 'A'; cout << "输入最后一个大写字母: "; cin >> input; for(int i = 1; i <= (input-'A'+1); ++i) { for(int j = 1; j <= i; ++j) { cout << alphabet << " "; } ++alphabet; cout << endl; } return 0; }

以上程序执行输出结果为:

A
B B
C C C
D D D D
E E E E E

实例


#include <iostream> using namespace std; int main() { int rows; cout << "输入行数: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int j = 1; j <= i; ++j) { cout << "* "; } cout << endl; } return 0; }

以上程序执行输出结果为:

* * * * *
* * * *
* * * 
* *
*

实例


#include <iostream> using namespace std; int main() { int rows; cout << "输入行数: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int j = 1; j <= i; ++j) { cout << j << " "; } cout << endl; } return 0; }

以上程序执行输出结果为:

1 2 3 4 5
1 2 3 4 
1 2 3
1 2
1

实例


#include <iostream> using namespace std; int main() { int space, rows; cout <<"输入行数: "; cin >> rows; for(int i = 1, k = 0; i <= rows; ++i, k = 0) { for(space = 1; space <= rows-i; ++space) { cout <<" "; } while(k != 2*i-1) { cout << "* "; ++k; } cout << endl; } return 0; }

以上程序执行输出结果为:

        *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

实例


#include <iostream> using namespace std; int main() { int rows, count = 0, count1 = 0, k = 0; cout << "输入行数: "; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int space = 1; space <= rows-i; ++space) { cout << " "; ++count; } while(k != 2*i-1) { if (count <= rows-1) { cout << i+k << " "; ++count; } else { ++count1; cout << i+k-2*count1 << " "; } ++k; } count1 = count = k = 0; cout << endl; } return 0; }

以上程序执行输出结果为:

        1
      2 3 2
    3 4 5 4 3
  4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

实例


#include <iostream> using namespace std; int main() { int rows; cout << "输入行数: "; cin >> rows; for(int i = rows; i >= 1; --i) { for(int space = 0; space < rows-i; ++space) cout << " "; for(int j = i; j <= 2*i-1; ++j) cout << "* "; for(int j = 0; j < i-1; ++j) cout << "* "; cout << endl; } return 0; }

以上程序执行输出结果为:

* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *

实例


#include <iostream> using namespace std; int main() { int rows, coef = 1; cout << "Enter number of rows: "; cin >> rows; for(int i = 0; i < rows; i++) { for(int space = 1; space <= rows-i; space++) cout <<" "; for(int j = 0; j <= i; j++) { if (j == 0 || i == 0) coef = 1; else coef = coef*(i-j+1)/j; cout << coef << " "; } cout << endl; } return 0; }

以上程序执行输出结果为:

           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1 

实例


#include <iostream> using namespace std; int main() { int rows, number = 1; cout << "输入行数: "; cin >> rows; for(int i = 1; i <= rows; i++) { for(int j = 1; j <= i; ++j) { cout << number << " "; ++number; } cout << endl; } return 0; }

以上程序执行输出结果为:

1
2 3
4 5 6
7 8 9 10

用户输入两个数,求这两个数的最大公约数。

实例


#include <iostream> using namespace std; int main() { int n1, n2; cout << "输入两个整数: "; cin >> n1 >> n2; while(n1 != n2) { if(n1 > n2) n1 -= n2; else n2 -= n1; } cout << "HCF = " << n1; return 0; }

以上程序执行输出结果为:

输入两个整数: 78
52
HCF = 26

实例


#include <iostream> using namespace std; int main() { int n1, n2, hcf; cout << "输入两个整数: "; cin >> n1 >> n2; // 如果 n2 大于 n1 交换两个变量 if ( n2 > n1) { int temp = n2; n2 = n1; n1 = temp; } for (int i = 1; i <= n2; ++i) { if (n1 % i == 0 && n2 % i ==0) { hcf = i; } } cout << "HCF = " << hcf; return 0; }

以上程序执行输出结果为:

输入两个整数: 78
52
HCF = 26

用户输入两个数,其这两个数的最小公倍数。

实例


#include <iostream> using namespace std; 
int main() { 
int n1, n2, max; 
cout << "输入两个数: "; 
cin >> n1 >> n2; 
// 获取最大的数 
max = (n1 > n2) ? n1 : n2; 
do { 
      if (max % n1 == 0 && max % n2 == 0) { 
            cout << "LCM = " << max; break; 
      } else ++max; 
  } while (true); 
return 0; 
}

以上程序执行输出结果为:

输入两个数: 12
18
LCM = 36

实例

#include <iostream> using namespace std; 
int main() { 
     int n1, n2, hcf, temp, lcm; 
     cout << "输入两个数: "; 
     cin >> n1 >> n2; 
     hcf = n1; 
     temp = n2; 
     while(hcf != temp) { 
        if(hcf > temp) hcf -= temp; else temp -= hcf; 
     } 
     lcm = (n1 * n2) / hcf; 
     cout << "LCM = " << lcm; 
     return 0; 
 }

以上程序执行输出结果为:

输入两个整数: 78
52
HCF = 156

使用 C++ 创建一个简单的计算器,可以实现 +, -, *, / 。

实例

#include <iostream>
using namespace std;
 
int main()
{
    char op;
    float num1, num2;
 
    cout << "输入运算符:+、-、*、/ : ";
    cin >> op;
 
    cout << "输入两个数: ";
    cin >> num1 >> num2;
 
    switch(op)
    {
        case '+':
            cout << num1+num2;
            break;
 
        case '-':
            cout << num1-num2;
            break;
 
        case '*':
            cout << num1*num2;
            break;
 
        case '/':
            if (num2 == 0)
            {
                cout << "error不能除以零";
                break;
            }
            else
            {
                cout << num1 / num2;
                break;
            }
 
        default:
            // 如果运算符不是 +, -, * 或 /, 提示错误信息
            cout << "Error!  请输入正确运算符。";
            break;
    }
 
    return 0;
}

以上程序执行输出结果为:

输入运算符:+、-、*、/ : +
输入两个数: 1
2
3

实例 2

#include <iostream>
 
using namespace std;
 
double add(double num1, double num2) {
    return num1 + num2;
}
 
double subtract(double num1, double num2) {
    return num1 - num2;
}
 
double multiply(double num1, double num2) {
    return num1 * num2;
}
 
double divide(double num1, double num2) {
    if (num2 != 0) {
        return num1 / num2;
    } else {
        cout << "错误:除数不能为零!" << endl;
        return 0;
    }
}
 
int main() {
    double num1, num2;
    char op;
 
    cout << "请输入第一个数字:";
    cin >> num1;
 
    cout << "请输入运算符(+、-、*、/):";
    cin >> op;
 
    cout << "请输入第二个数字:";
    cin >> num2;
 
    double result;
 
    switch (op) {
        case '+':
            result = add(num1, num2);
            break;
        case '-':
            result = subtract(num1, num2);
            break;
        case '*':
            result = multiply(num1, num2);
            break;
        case '/':
            result = divide(num1, num2);
            break;
        default:
            cout << "错误:无效的运算符!" << endl;
            return 0;
    }
 
    cout << "结果:" << result << endl;
 
    return 0;
}

以上程序执行输出结果为:

请输入第一个数字:4
请输入运算符(+、-、*、/):/
请输入第二个数字:2
结果:2

一只小猴子一天摘了许多桃子,第一天吃了一半,然后忍不住又吃了一个;第二天又吃了一半,再加上一个;后面每天都是这样吃。到第10天的时候,小猴子发现只有一个桃子了。问小猴子第一天共摘了多少个桃子。

实例

#include <iostream> using namespace std; 
int main() { 
    int x, y, n; 
    for (x=1, n=0; n<9; y=(x+1)*2, x=y, n++); 
        cout<<"第一天共摘的桃子数量为 "<<x<<endl; 
    return 0; 
}

以上实例输出结果为:

第一天共摘的桃子数量为 1534