C++第二章部分例题及习题

发布时间 2023-04-12 22:07:49作者: 石铁生

例2-9

分析:先输出前面四行,然后输出后三行。前四行空格部分用行数乘以2在用八减,符号用行数乘以2减一。后三行符号部分用行数乘以2减一。

流程图:

 

代码部分:

#include<iostream>
using namespace std;
int main()
{
    for (int i = 4; i > 0; i--)//对前四行进行循环输出
    {
        for (int j = 30; j > 0; j--)
        {
            cout << " ";
        }
        for (int j = 2*i-1; j >0; j--)
        {
            cout << " ";
        }
        for (int j = 0; j <= 8 - 2 * i ;j++)
        {
            cout << "*";
        }
        cout << endl;
    }
    for (int i = 3; i > 0; i--)//对后三行进行循环输出
    {
        for (int j = 30; j > 0; j--)
        {
            cout << " ";
        }
        for (int j = 2 * i - 1; j > 0; j--)
        {
            cout << "*";
        }
        cout << endl;
    }
    return 0;
}

 例2-10

读入一系列整数,统计出正整数个数i和负整数个数j,读入0则结束。

分析:读入数字判断是否为零,若为零结束,否则继续循环读入,用两个数别统计个数。

流程图:

代码流程:

#include<iostream>
using namespace std;
int main()
{
    int a=0, b=0;
    int x;
    do {
        cin >> x;
        if (x > 0)//计算整数个数
            a++;
        if (x < 0)//计算负数个数
            b++;
    } while (x != 0);//当检测到0是停止循环
    cout << "正数个数" << a << endl;
    cout << "负数个数" << b << endl;
    return 0;
}

习题2-14

修改代码

 

#include<iostream>
using namespace std;
int main()
{
    int i;
    int j;
    i = 10;
    j = 20;
    cout << "i+j=" << i + j;
    return 0;
}

 

习题2-15

编写一个程序,运行时提示输入一个数字,再把这个数字显示出来。

#include<iostream>
using namespace std;
int main()
{
    int x;
    cout << "请输入一个数字" << endl;
    cin >> x;
    cout << x;
    return 0;
}

习题2-16

输出ASCII为32~127的字符

 

#include<iostream>
using namespace std;
int main()
{
    for (int i = 32; i <= 127; i++)
    {
        printf("%c", i);
        cout <<"   ";
}
    return 0;
}

 

习题2-24

 分析:用do...while循环向用户提问,当得到正确的回答时跳出循环。

using namespace std;
int main()
{
    char x;
    do {
        cout << "现在正在下雨吗?" << endl;
        
        cin >> x;
        if (x == 'Y')
        {
            cout << "现在正在下雨。" << endl;
        }
        else if (x == 'N')
        {
            cout << "现在没有下雨。" << endl;
        }
    } while (x != 'Y' && x != 'N');
    return 0;

习题2-25

分析:用else if进行判断选择和输出。

#include<iostream>
using namespace std;
int main()
{
    int x;
    cin >> x;
    if (x >= 90 && x <= 100)
    {
        cout << "" << endl;
    }
    else if (x >= 80 && x < 90)
    {
        cout << "" << endl;
    }
    else if (x >= 60 && x < 80)
    {
        cout << "" << endl;
    }
    else if (x >= 0 && x < 60)
    {
        cout << "" << endl;
    }
    return 0;
}

 例2-26

#include<iostream>
using namespace std;
int main()
{
    cout << "Menu:A(dd)D(elete)S(ort)Q(uit),Select one:" << endl;
    char x;
    
    do {
        cin >> x;
        if (x == 'A')
            cout << "数据已经增加。" << endl;

        else if (x == 'D')
            cout << "数据已经删除。" << endl;
        else if (x == 'S')
            cout << "数据已经排序。" << endl;
    } while (x != 'Q');
    return 0;
}