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.
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;
}
It is definitely possible. The question is what you want to do. Is
if(second > first + x) {
cout << "second x or more than x bigger than first" << endl;
} else if(second + x < first) {
cout << "second x or more smaller than first" << endl;
} else {
cout << "second - x > first > second + x" << endl;
}
what you like? Of course second, first and x should have the same data type; you shouldn't carelessly mix int and double.
I am not sure about your question but I think you mean:
int main() {
int first;
int second;
cin>>first;
cin>>second;
if (second >first + 0.5) {
}
If you want second be AT LEAST 0.5 bigger than first. If this is not, reprhase your question please
Use the ternary operator:
int main()
{
double first;
double second;
cin >> first;
cin >> second;
(second - first > 0.5) ? cout << "Too Big!\n" : ( (second - first < 0.5) ? cout << "Too low\n" : cout << "Calculation will be made\n"; );
}
The format is: < condition > ? < true-case-code > : < false-case-code >;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.