You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言买卖程序中按15%概率用printf输出指定提示?

实现商品15%概率显示无货的解决方案

要给每个商品添加15%概率显示「今日无货」的逻辑,核心思路是通过随机数判断概率:生成0-99的整数,当数值落在0-14区间时(占比15%),输出无货提示,否则展示生成好的价格。

修改后的完整可运行代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int item1, item2, item3;
    srand(time(NULL));

    // 生成指定范围的商品基础价格
    item1 = rand() % (1000 - 500 + 1) + 500;
    item2 = rand() % (5000 - 1500 + 1) + 1500;
    item3 = rand() % (8000 - 5000 + 1) + 5000;

    // Item1:15%概率显示无货,否则显示价格
    if (rand() % 100 < 15) {
        printf("The Price of Item1 is: 今日无货\n");
    } else {
        printf("The Price of Item1 is %dG\n", item1);
    }

    // Item2:独立概率判断
    if (rand() % 100 < 15) {
        printf("The Price of Item2 is: 今日无货\n");
    } else {
        printf("The Price of Item2 is %dG\n", item2);
    }

    // Item3:独立概率判断
    if (rand() % 100 < 15) {
        printf("The Price of Item3 is: 今日无货\n");
    } else {
        printf("The Price of Item3 is %dG\n", item3);
    }

    return 0;
}

关键点说明

  • 概率判断:rand() % 100生成0-99的随机整数,0-14共15个数值刚好对应15%的概率阈值。
  • 独立性:每个商品单独调用rand()做判断,确保三个商品的无货概率互不影响。
  • 自定义提示:如果需要保留英文提示,直接把「今日无货」替换为"not available today"即可。

内容的提问来源于stack exchange,提问作者ae winter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:55:28