如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句

If the difference between 2 numbers is between 1 and 100 it should run an if statement

本文关键字:之间 if 运行 语句 数字 如果      更新时间:2023-10-16

我不确定为什么说"数字接近"的if语句没有运行?

我已经用数字对其进行了测试,以在 1-100 之间产生差异。

有什么想法吗?

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
    double num1, num2, difference;

    while(num1 != 100 || num2 != 200)
    {
        cout << "Enter a number:" << endl ;
        cin >> num1 ;
        cout << "Enter a 2nd number: " << endl ;
        cin >> num2 ;
        if (num1 == num2)
            { cout << "the numbers are equal" << endl ;
            }
        else if (num1 > num2)
        {   cout << "The larger number is num1:" << num1 << endl ;
            cout << "The smaller number is num2:" <<num2 << endl;
            difference = num1- num2;
           if (difference <100 && difference > 1)
            {
            cout << "Numbers are almost equaln" ;
            }
            else
            {}
        }
    else if (num2 - num1)
        {   cout << "The larger number is num2:" << num2 << endl ;
            cout << "The smaller number is num1:" <<num1 << endl;
        }

    }
    return 0;
}

亲切问候

而不是

difference = num1- num2;

你需要

difference = fabs(num1- num2);

否则,"接近度"测试仅在num1大于 num2 时才有效。

还要确保在while循环之前初始化num1num2

double num1 = 0;
double num2 = 0;
double difference = 0;  // Just for consistency
while ( ... )
{
   ...
}
您应该

使用 abs 来获取 2 个数字之差的绝对值。

此外,您的外观也存在一些问题,主要是调用尚未赋予值的变量,请尝试下面的代码,它应该完成您想要完成的任务。

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main() {
  bool again = true;
  while(again){
    double num1, num2, diffrence;
    cout << "Enter a Number: " << endl;
    cin >>num1; 
    cout << "Enter a 2nd Number: " << endl;
    cin >> num2;
    diffrence = abs(num1-num2);
    if(diffrence==0){
        cout << "the numbers are equal";
    }else{
      if(num1>num2){
        cout << "the larger number is num1: " << num1 << endl;
        cout << "the smaller number is num2: " << num2 << endl;
      }else{
        cout << "the larger number is num2: " << num2 << endl;
        cout << "the smaller number is num1: " << num1 << endl;
      }  
      if(diffrence<100){
        cout << "Numbers are almost equaln";
      }else{
        cout << "Numbers are not even close";
      }
    }
    cout << "Try again (y/n)?" << endl;
    char response;
    cin >> response;
    if(tolower(response)=='n'){
      again = false;
    }
  }
  return 0;
}
auto x = main();