为什么我的rand()数字为0?

时间:2012-09-23 19:18:25

标签: c++ visual-studio-2010

这是我正在制作的类的函数成员,它不会导致任何语法错误只是语义错误。它应该产生的随机数为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;
}

请帮忙! 谢谢, 〜卡塔纳

1 个答案:

答案 0 :(得分:2)

可能缺少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");
 }