我正在尝试在FPS统一游戏中对系统进行编程,其中每当您耗尽12枚子弹时,该程序就会从库存堆中提取另外12枚。问题是,如果库存堆大于12,而您耗尽了已经装入枪支的12发子弹,则整个库存就会消失。我已经扫描了我的代码,并对如何解决此错误感到完全困惑。该操作的主要代码如下。
if (bulletsLeft <= 1)
{
if (extraBullets > 0)
{
if (extraBullets <= 12)
bulletsLeft += extraBullets;
extraBullets -= extraBullets;
}
if (extraBullets >= 12)
{
bulletsLeft += 12;
extraBullets -= 12;
}
}
答案 0 :(得分:2)
因为忘记了花括号,所以您的代码...
// [[Rcpp::depends(dqrng, BH, RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <boost/random/binomial_distribution.hpp>
#include <xoshiro.h>
#include <dqrng_distribution.h>
// [[Rcpp::plugins(openmp)]]
#include <omp.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
arma::mat parallel_random_matrix(int n, int m, int ncores, double p=0.5) {
dqrng::xoshiro256plus rng(42);
arma::mat out(n*m,3);
// ok to use rng here
#pragma omp parallel num_threads(ncores)
{
dqrng::xoshiro256plus lrng(rng); // make thread local copy of rng
lrng.jump(omp_get_thread_num() + 1); // advance rng by 1 ... ncores jumps
int iter = 0;
#pragma omp for
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
iter = i * n + j;
// p can be a function of i and j
boost::random::binomial_distribution<int> dist_binomial(1,p);
auto gen_bernoulli = std::bind(dist_binomial, std::ref(lrng));
boost::random::normal_distribution<int> dist_normal1(2.0,1.0);
auto gen_normal1 = std::bind(dist_normal1, std::ref(lrng));
boost::random::normal_distribution<int> dist_normal2(4.0,3.0);
auto gen_normal2 = std::bind(dist_normal2, std::ref(lrng));
out(iter,0) = gen_bernoulli();
out(iter,1) = 2.0;//gen_normal1();
out(iter,2) = 3.0;//gen_normal2();
}
}
}
// ok to use rng here
return out;
}
/*** R
parallel_random_matrix(5, 5, 4, 0.75)
*/
...等同于
if (extraBullets <= 12)
bulletsLeft += extraBullets;
extraBullets -= extraBullets;
下一条语句...
if (extraBullets <= 12) {
bulletsLeft += extraBullets;
}
extraBullets -= extraBullets; // No more bullets after this!
...将永远不会执行。
我建议简化逻辑,并首先确定要从库存堆中转移多少发子弹。然后执行转移。
if (extraBullets >= 12)
具有三元表达式的赋值...
if (bulletsLeft <= 1) {
int transferBullets = extraBullets < 12 ? extraBullets : 12;
bulletsLeft += transferBullets;
extraBullets -= transferBullets;
}
...等同于
int transferBullets = extraBullets < 12 ? extraBullets : 12;
根据@Kyle和@UnholySheep,您也可以这样写:
int transferBullets;
if (extraBullets < 12) {
transferBullets = extraBullets;
} else {
transferBullets = 12;
}