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

本文介绍了使用C++编写的三个程序:判断一个数是否为质数,猜数字游戏以及用符号绘制心形图案的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断质数

#include<iostream>

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<iostream>
#include<ctime>

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<iostream>
#include<cmath>


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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值