抱歉,如果问题不清楚,英语不是我的主要语言,所以我不知道如何撰写它。我的老师做了一个练习,根据健康和攻击力来计算谁会在决斗中获胜。我想对其进行一些扩展,并添加护甲、暴击几率和暴击伤害作为额外的统计数据,现在我正在尝试弄清楚如何在伤害中应用暴击几率。这是我到目前为止所得到的。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int HP;
int damage;
int armor;
float crit_damage;
float crit_chance;
} atributes;
//how to implement crit_chance?
//using a function?
//divide 100 for the crit_chance
//Ex: crit_chance = 25 ; 100/25 = 4
//generate a random number between 1 and 4
//if the number is 4 the crit_chance is sucessfull
//if not then the crit_chance fails
//aply then the result of the funcion to character[i].crit_damage
int main() {
int i, rounds = 0;
atributes character[2];
for(i = 0; i < 2; i++) {
printf("\tCharacter %d atributes\n", i+1);
printf(" Damage = ");
scanf("%d", &character[i].HP);
printf(" HP = ");
scanf("%d", &character[i].damage);
printf(" Armor = ");
scanf("%d", &character[i].armor);
printf(" Crit Damage = ");
scanf("%f", &character[i].crit_damage);
printf(" Crit Chance = ");
scanf("%f", &character[i].crit_chance);
printf("\n");
}
while ((character[0].HP > 0) || (character[1].HP > 0)) {
character[0].HP -= (character[1].damage * (character[1].crit_damage) - character[0].armor * 2);
character[1].HP -= (character[0].damage * (character[0].crit_damage) - character[1].armor * 2);
rounds++;
};
if (character[0].HP > character[1].HP) printf("\tCharacter 1 won after %d rounds!", rounds);
else if (character[0].HP < character[1].HP) printf("\tCharacter 2 won after %d rounds!", rounds);
else printf("\tThe duel ended in a tie after %d rounds", rounds);
return 0;
}
最佳答案
类似于以下作品:
int is_critical = (rand()%4==3);
rand()
是 stdlib.h
提供的函数,它返回一个介于 0
和 RAND_MAX
之间的值>(stdlib.h
中定义的常量)。
rand()%4
给出该值除以 4 后的余数:这将是数字 0、1、2 或 3。
询问rand()%4==3
询问结果是否等于 3(尽管您也可以选择 0、1 或 2)。由于 3 代表 25% 的结果,因此这对应于您想要的结果,如果命中,则 is_ritic
为 1。
但需要注意的是,由于 RAND_MAX
可能无法被 4 整除,因此某些模数结果出现的几率稍高,因此您永远不会希望以这种方式为任何真正重要的事情(科学、金融、加密货币等)生成随机数。
您可以将此方法概括如下:
int is_critical = (rand()/(float)RAND_MAX)>0.75;
由于 rand()
和 RAND_MAX
都给出整数,并且 RAND_MAX
大于 rand()
,因此除以它们给出 0。因此我们将 RAND_MAX
转换为 float 。结果是 0-1 范围内的“均匀”分布的数字。该值大于 0.75,概率为 25%,这正是您想要的。
关于c - 如何计算应用加成的几率(即暴击几率)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314191/