pxxfxxxxx

导航

C++起航

1.1 C++输入与输出

#include <iostream>
#include <stdlib.h>
using namespace std;

//要求:用户输入一个整数,将该整数分别以8进制,10进制,16进制打印在屏幕上
//要求:提示用户输入一个布尔值(0 或 1),以布尔方式打印在屏幕上

int main() {
    cout << "Please enter a number:" << endl;//输出
    int x = 0;
    cin >> x;//输入
    cout << oct << x << endl;// 八进制
    cout << dec << x << endl;// 十进制
    cout << hex << x << endl;//16进制9

    cout << "请输入一个布尔值(0或1):" << endl;
    bool y = false;
    cin >> y;
    cout << boolalpha << y << endl; //boolalpha,函数名称,功能是把bool值显示为true或false
    system ("pause"); //系统暂停
    return 0;

     }
     
     Please enter a number:
17
21
17
11
请输入一个布尔值(0或1):
0
false
请按任意键继续. . .

Process returned 0 (0x0)   execution time : 26.941 s
Press any key to continue.

1.2 namespace

 1 #include <stdlib.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 namespace A{
 6     int x = 1;
 7     void fun() {
 8     cout << "A" << endl;
 9     }
10     void fun2() {
11     cout << "2A" << endl;
12     }
13 }
14 
15 namespace B{
16     int x = 7;
17     void fun4() {
18     cout << "U" << endl;
19     }
20 }
21 
22 int main() {
23     cout << A::x << endl;
24     B::fun4();
25     A::fun2();
26     system("pause");
27     return 0;
28 }
29 
30 1
31 U
32 2A
33 请按任意键继续. . .
34 
35 Process returned 0 (0x0)   execution time : 17.504 s
36 Press any key to continue.

1.3 综合练习

题目:使用一个函数找出一个整型阵列中的最大值,最小值

#include <stdlib.h>
#include <iostream>
using namespace std;

int getMaxOrMin (int *arr, int count, bool isMax)
{
    int temp = arr[0];
    for (int i = 1; i < count; i++)
    {
        if (isMax)
        {
            if (temp < arr[i])
            {
            temp = arr[i];
            }
        else
        {
            if (temp > arr[i])
            {
            temp = arr[i];
            }
        }
        }
        }
    return temp;
}


int main(void)
{
    int arr1[4] = {3, 4, 7, 9};
    bool isMax = false;
    cout << "你想要最大值还是最小值呢:" << endl;
    cin >> isMax;
    cout << getMaxOrMin(arr1, 4, isMax) << endl;
    system("pause");
    return 0;
}
你想要最大值还是最小值呢:
1
9
请按任意键继续. . .

注意:括号要对齐

用命名空间

 

#include <stdlib.h>
#include <iostream>
using namespace std;

namespace compA
{
    int getMaxOrMin (int *arr, int count, bool isMax)
{
    int temp = arr[0];
    for (int i = 1; i < count; i++)
    {
        if (isMax)
        {
            if (temp < arr[i])
            {
            temp = arr[i];
            }
        else
        {
            if (temp > arr[i])
            {
            temp = arr[i];
            }
        }
        }
        }
    return temp;
}
}



int main(void)
{
    int arr1[4] = {3, 4, 7, 9};
    bool isMax = false;
    cout << "你想要最大值还是最小值呢:" << endl;
    cin >> isMax;
    cout << compA::getMaxOrMin(arr1, 4, isMax) << endl;
    system("pause");
    return 0;
}

 

posted on 2019-05-21 11:22  pxxfxxxxx  阅读(115)  评论(0编辑  收藏  举报