Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我的rand()数显示为0?_C++_Visual Studio 2010 - Fatal编程技术网

C++ 为什么我的rand()数显示为0?

C++ 为什么我的rand()数显示为0?,c++,visual-studio-2010,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() %

这是我正在创建的类的函数成员,它不会导致任何语法错误,只是语义错误。它应该组成的随机数是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;
}
int-Warrior::attack()
{
int hit=0;
开关(武器)
{
案例6:
命中率=兰德()%(5-1+1)+1;
打破
案例7:
命中率=兰德()%(10-4+1)+4;
打破
案例8:
命中率=兰德()%(15-9+1)+9;
打破
案例9:
命中率=兰德()%(20-14+1)+14;
打破
案例10:
命中率=兰德()%(25-19+1)+19;
打破
}

std::cout可能是因为缺少
默认的
开关语句,即
武器
没有触发任何
开关
子句

尝试:


武器
在[6,10]范围内吗?似乎不在范围内。请注意,如果没有找到匹配的案例,您已将
命中
定义为0。@sftrabbit是(游戏中将有6件武器,一把青铜剑由6表示)。不要使用硬编码的数字作为武器索引,请使用
enum
。此外,我建议您创建一个函数
getRand(inta,intb)
来生成
rand()%(a-b+1)+b
行。@katana7070 Print
武器
,我想您可能会感到惊讶。
 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");
 }