[英]Compare two numbers if the difference is higher/lower than 'x', do something
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.因此,在此示例中,当第二个数字与第一个数字相比介于 0.5 之间时,代码将继续执行。
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.这将检查 2 个数字之间的差异是否符合您想要的标准。 Also, change the types of your numbers to
double
, since currently truncation will compare the wrong numbers.此外,将您的数字类型更改为
double
,因为当前截断将比较错误的数字。 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;
当然第二,first和x应该有相同的数据类型; you shouldn't carelessly mix int and double.
你不应该不小心混用 int 和 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.如果你想要第二个至少比第一个大 0.5。 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 >;
<真案例代码>:<假案例代码>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.