为什么我的 rand() 数字显示为 0

Why does my rand() number come up as 0?

本文关键字:数字显示 我的 rand 为什么      更新时间:2023-10-16

这是我正在制作的类的函数成员,它不会导致任何语法错误,只是语义错误。它应该组成的随机数显示为 0。

int Warrior::attack()
{
int hit = 0;
 switch (weapon)
{
case 6:
     hit = rand() % (5 - 1 + 1) + 1; 
     break;
case 7:
     hit = rand() % (10 - 4 + 1) + 4;
     break;
case 8:
     hit = rand() % (15 - 9 + 1) + 9;
     break;
case 9:
     hit = rand() % (20 - 14 + 1) + 14;
     break;
case 10:
      hit = rand() % (25 - 19 + 1) + 19;
      break;
 }
std::cout<< "You hit " << hit <<"!n";
 return hit;
}

请帮忙!谢谢~武士刀

可能是缺少default开关语句,即 weapon不会触发任何switch条款。

尝试:

 switch (weapon)
{
case 6:
     hit = rand() % (5 - 1 + 1) + 1; 
     break;
case 7:
     hit = rand() % (10 - 4 + 1) + 4;
     break;
case 8:
     hit = rand() % (15 - 9 + 1) + 9;
     break;
case 9:
     hit = rand() % (20 - 14 + 1) + 14;
     break;
case 10:
      hit = rand() % (25 - 19 + 1) + 19;
      break;
default:
      throw std::exception("switch statement failed");
 }