第二章部分习题

用穷举法找出1~100中的质数

代码:

using namespace std;
int main()
{
    
    int k = 1;
    for (int i = 1; i <= 99; i++)
    {
        k++;
        int a = 0;
        for (int j = 2; j <= i / 2; j++)
        {
            if (k% j == 0)
            {
                a = 1;
            }
        }
        if (a != 1)
        {
            cout << k;
            cout << " ";
        }
    }

    return 0;
}

例2-29

代码:

using namespace std;
int main()
{
    srand((unsigned int)time(NULL));
    int a = rand() % 100 + 1;//生成1~100的随机数
    int b;
    do {
        cin >> b;
        if (a < b)
        {
            cout << "大了" << endl;
        }
        else if (a > b)
        {
            cout << "小了" << endl;
        }
        else
            cout << "猜对了" << endl;
    } while (a != b);

    return 0;
}

例2-31

 代码部分:

#include<iostream>
#include<time.h>
using namespace std;
int main()
{
    int k, f;
    for (int i = 1; i <= 9; i++)
    {
        for (int j = 1; j <= 9; j++)
        {
            cout << i << "*" << j << "="<<i*j<<"   ";
        }
        cout << endl;
    }

    return 0;
}

 

posted on 2023-04-13 22:14  石铁生  阅读(21)  评论(0)    收藏  举报