Jeroen - 11 months ago 39

C++ Question

I am wondering whether it is possible to write a code that commpares two numbers and when the second number is 'x' higher/lower than the first number do something. I wrote an example code to make it a bit more clear. Help is appreciated, thanks!

`int main()`

{

int first = 0;

int second = 0;

cin >> first;

cin >> second;

if (second = 0.5 > first) //I assumed it would look close to this. This obv isnt working but I cant figure out the correct way.

{

cout << "Too big\n";

}

else if (second = 0.5 < first)

{

cout << "Too low\n";

}

else {

cout << "Calculation will be made\n";

}

return 0;

}

So in this example, when the second number is between the range of 0.5 compared to the first number the code will proceed.

Answer Source

If you want the amount to check by a certain amount, change your condition to this:

```
if (second - first > 0.5)
{
cout << "Too Big!\n";
}
else if (second - first < 0.5)
{
cout << "Too low\n";
}
```

This would check if the difference between the 2 nunbers fits the criteria you want. Also, change the types of your numbers to `double`

, since currently truncation will compare the wrong numbers. For example in checking the value with a variable, try this:

```
int main()
{
double first = 0;
double second = 0;
double x = 0;
cin >> first;
cin >> second;
cin >> x;
if (second - first > x) {
cout << "Too Big!\n";
}
else if (second - first < x) {
cout << "Too low\n";
}
else {
cout << "Calculation will be made\n";
}
return 0;
}
```