c++ 小案例:判断质数&&猜数字&&用符号填补心形图案

文章目录

  • 判断质数
  • 猜数字
  • 用符号填补心形图案

判断质数

#include

using namespace std;

bool isprime(int num)
{
    int i = 2;
    while(i < num)
    {
        if (num % i == 0)
        {
            return false;
        }
        ++i;
    }
    return true;
}

int main()
{
    cout << "请输入一个不超过20亿的自然数" << endl;
    int num;
    cin >> num;

    

    if(isprime(num))
    {
        cout << "是质数" << endl;
    }
    else
    {
        cout << "不是质数" << endl;
    }

    cin.get();
    cin.get();
}

猜数字

#include
#include

using namespace std;

int rand_int()
{
    srand(time(0));
    int random_num = rand() % 100;
    return random_num;
}



bool game_progress(int random_num)
{
    int guess_num;
    int i = 5;
    int low = 0, high = 100;
    while(i > 0)
    {
        cout << "请输入一个" << low <<"~" << high <<"的数字。" << "你还有" << i << "次机会"<< endl;
        cin >> guess_num;
        if(guess_num == random_num)
        {
            return true;
        }
        else if(guess_num > random_num)
        {
            high = guess_num;
        }
        else
        {
            low = guess_num;
        }
        --i;
    }
    return false;
}

void print_result(bool result, int random_num)
{
    if(result)
    {
        cout << "恭喜你答对了" << endl;
    }
    else
    {
            cout << "游戏失败!你的机会已经用完,正确结果是:" << random_num << endl;
    }
}


int main()
{
    int random_num;
    random_num = rand_int();
    cout << "现在已产生一个0~100的数字,请你猜猜看,注意你只有5次机会噢。" << endl;

    bool result;
    result = game_progress(random_num);
    print_result(result, random_num);
}

用符号填补心形图案

#include
#include


using namespace std;

void draw_heart()
{
    // (x^2 + y^2 - a)^3 - x^2 * y^3 = 0
    double a = 1;
    double bound = 1.3 * sqrt(a);
    double y_step = 0.05;
    double x_step = 0.025;

    for(double y = bound; y >= -bound; y -= y_step)
    {
        for(double x = bound; x >= -bound; x -= x_step)
        {
            double result = pow((pow(x, 2) + pow(y, 2) - a), 3) - pow(x, 2) * pow(y, 3);
            if(result > 0)
            {
                cout << " ";
            } 
            else
            {
                cout << "*";
            }
        }
        cout << endl;
    }
    cin.get();  
    cin.get();
}

int main()
{
    draw_heart();
}

你可能感兴趣的:(C++学习记录,c++,算法,开发语言)