How to set minimum and maximum values for an integer? - css

How do i add minimum and maximum values for an integer? I want an integer to never go down below zero like negative and never goes above 100
Here is the example:
int hp = 100;
std::cout << "You cast healing magic to yourself!" << std::endl;
hp += 20;
mp -= 25;
For example the health is 100 but when a healing magic is cast it became 120. The thing i want is i want it to stay as 100 no matter how many healing magic are cast upon.

You can use std::clamp:
hp = std::clamp(hp + 20, 0, 100);
mp = std::clamp(mp - 25, 0, 100);

You can use std::clamp as suggested by #TedLyngmo if you are using a compiler which supports C++ 17. If not, then you can write a simple function to manage the limits for hp and mp:
void change(int& orig, int val)
{
int temp = orig + val;
if (temp <= 0)
temp = 0;
else if (temp >= 100)
temp = 100;
orig = temp;
}
int main()
{
int hp = 40, mp = 40;
std::cout << "You cast healing magic to yourself!" << std::endl;
change(hp, 50);
change(mp, -25);
std::cout << hp << " " << mp << std::endl;
}

I believe what you are saying is whatever the healing magic is you want to display 100 or your hp the way it is. If so you can store the 20 and 25 as variables and create another var with the same value as ur original one and play around with that. Don't change the value of ur original one and so you get to display that.

Related

hello, what is my mistake in writing this code? its not displaying the last 3 bullet points properly

Some insurance companies offer discounts on car insurance premiums depending on the number of years the driver has had a driver's licence and the number of claims the driver has made in the last five years.
In this program, the user inputs (as integers)
•years the number of years the driver has had a driver's license
•claims the number of insurance claims made in the last five years
The (integer) percentage of the "standard premium"that will be charged is initially calculated as follows:
•if years< 5 then percentage = 100 –10 * years + 20 * claims
•otherwise ("else") percentage = 50 + 20 * claims
The percentage calculated in this way is then further adjusted as follows:
•if percentage> 150 then insurance is refused
•otherwise,if the percentage is between 100% and 150% then set percentage = 100
•(otherwise,the percentage isn't adjusted)
cout << "enter years licenced: " << endl;
cin >> years;
cout << "enter number of claims: " << endl;
cin >> claims;
if (years < 5)
{
percentage = 100 - (10 * years) + (20 * claims);
cout << "percentage from 0 to 5:" << percentage << endl;
}
else (years > 5);
{
percentage = 50 + (20 * claims);
cout << "percentage higher than 5:" << percentage << endl;
}
if (percentage > 150)
{
cout << "insurance is refused." << percentage << endl;
}
else if (100 <= percentage <= 150)
{
cout << "percentage = 100." << endl;
}
else;
{
cout << "insurance is refused." << endl;
}
return 0;
Replace
else if (100 <= percentage <= 150)
with
else if (100 <= percentage && percentage <= 150)
In C++, chaining of comparison operators works differently than in math. To get the math meaning, don't use chaining, and connect individual comparisons with logical and (&&).
Replace
else (years > 5);
with
else if (years > 5)
The ; is equivalent to {}, thus it makes the else branch empty, and the code below (the multiline {...}) would be executed unconditionally.
Replace
else;
with
else

Strange behavior when incrementally sampling using RcppArmadillo::sample

I'm trying to implement some draws using a polya urn scheme using Rcpp. Basically, I have a matrix I'm drawing from, and a 2nd matrix with weights proportional to the probabilities. After each draw, I need to increase the weight of whichever cell I drew.
I was running into some indexing errors which lead me to examine the sampling more generally, and I found that my weight matrix was getting modified by RcppArmadillo::sample. Two questions (1) is this behavior that I should have expected or is this a bug which I should report somewhere? (2) Any ideas on current work-around? Here's a reproducible example:
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp ;
// [[Rcpp::export]]
void sampler(int N, int inc, NumericMatrix& weight_matrix, int reps) {
IntegerVector wm_tmp = seq_along(weight_matrix);
Rcout << "Initial weight_matrix:\n" << weight_matrix << "\n";
int x_ind;
for(int i = 0; i < reps; ++i) {
x_ind = RcppArmadillo::sample(wm_tmp, 1, true, weight_matrix)(0) - 1;
Rcout << "Weight matrix after sample: (rep = " << i << ")\n" << weight_matrix << "\n";
Rcout << "x_ind: " << x_ind << "\n";
// get indices
weight_matrix[x_ind] = weight_matrix[x_ind] + inc;
Rcout << "Add increment of " << inc << " to weight_matrix:\n" << weight_matrix << "\n";
}
}
//
// // [[Rcpp::export]]
// IntegerVector seq_cpp(IntegerMatrix x) {
// IntegerVector tmp = seq_along(x);
// IntegerVector ret = RcppArmadillo::sample(tmp, 2, true);
// return ret;
// }
/*** R
weight_matrix <- matrix(1, 5, 2)
sampler(5, 1, weight_matrix, 3)
weight_matrix <- matrix(1, 5, 2)
sampler(5, 0, weight_matrix, 3)
*/
Thanks!
That is known and documented behaviour.
You could do
i) Use Rcpp::clone() to create a distinct copy of your SEXP (ie NumericMatrix).
ii) Use an Armadillo matrix instead and pass as const arma::mat & m.
There are architectural reasons having to do with the way R organizes its data structure which mean that we cannot give you fast access (no copies!) and also protect against writes.

How to round an int in Qt to the nearest 5

I am looking for a good way to round an int in Qt to the nearest 5.
e.g:
8 -> 10
12 -> 10
13 -> 15
15 -> 15
17 -> 15
and so on
Rounding in C++ to the nearest integer number usually is done via:
static_cast<int>(number + 0.5);
Now, to round it to the next 5, I would bring it into the system where we can apply this rounding rule (i.e. 5 -> 1, 6 -> 1.2) and then bring it back into the system where 5 really is 5:
int roundToNearestFive(int number)
{
return static_cast<int>(number / 5. + .5) * 5;
}
I find this formulation easiest.
Here a possible solution:
#include<iostream>
int toNearest5(int i) {
int r = i%5, o = 0;
if(r) {
o = r/5. >= .5 ? 5 : 0;
}
return (i-r+o);
}
int main() {
using namespace std;
cout << toNearest5(8) << endl;
cout << toNearest5(12) << endl;
cout << toNearest5(13) << endl;
cout << toNearest5(15) << endl;
cout << toNearest5(17) << endl;
}
The idea is to get the number and round it to the lowest multiple of 5 (you can do that by removing the remainder), that is:
int remainder = i%5;
int rounded = i - remainder;
Now, you can check the remainder and add 5 to the rounded number if the remainder is greater than 2.5, otherwise add 0.
In order to check it, I've divided the remainder by 5 (its upper bound), so that to get a number in [0,1[ and check it with 0.5 to know how to round the original number.
It follows a more compact version of the same function:
int toNearest5(int i) {
int j = i%5;
return (i - j + (j/5. >= .5 ? 5 : 0));
}
I don't know if the Qt framework offers something similar out of the box, but it's a matter of an one line function, you can easily write it for yourself.

trouble with output of recursive function

i'm having trouble getting the correct output of the function. The function output should show the expression. For example, if the input is "1234", then the output should be 1 + 2 + 3 + 4 = 10.
i can get the function to output the first part of the expression, but i'm not sure how to get it to output the sum as well.
heres what i have so far:
void sumDigits(int num, int &sum){
sum += num % 10;
if(num < 10)
cout << num;
else {
sumDigits(num/10, sum);
cout << " + " << num % 10;
}
}
why don't you do it in caller?
you could pass the remaining digits number to process to a function and output sum when it's 0, but I doing it in the caller is better..
<< can be chained. Try
cout << " + " << num % 10 << " = " << sum << endl;

Sampling from a distribution with a margin of error

The following code samples a weighted random distribution as part of a simulation representing the options 100k individuals may take (eg: voting etc).
There are two possible options with weights of 30% and 70% respectively.
#include <iostream>
#include <random>
int main()
{
int option0 = 30; //30%
int option1 = 70; //30%
std::vector<int> option({0,0});
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d({option0,option1});
for (int n=0; n < 100000; ++n)
{
++option[d(gen)];
}
std::cout << "Option 0: " << option[0] << std::endl;
std::cout << "Option 1: " << option[1] << std::endl;
return 0;
}
Question:
If the above percentages (weights) were derived by taking a survey of a population using sampling and the margin of error was determined to be 5%.
How would one go about modifying the above simulation to take into account (aka incorporate) the 5% margin of error?
Because you know exactly the margin of error, you can modify the weights with
a randomly generated double (between -5.0 and 5.0) and then run your proposed simulation.
This function will simulate the desired margin of error :
void
simulating_margin_of_error(std::mt19937 gen, double marginOfError,
int* option0, int* option1)
{
std::uniform_real_distribution<double>
distribution(-marginOfError,marginOfError);
double number = distribution(gen);
*option0 += (int) number;
*option1 += - (int) number;
}
And you can include it here :
[...]
std::mt19937 gen(rd());
simulating_margin_of_error(gen, 5.0, &option0, &option1);
std::discrete_distribution<> d({option0, option1});
[...]

Resources