如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
If the difference between 2 numbers is between 1 and 100 it should run an if statement
我不确定为什么说"数字接近"的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
循环之前初始化num1
和num2
。
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();
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在c代码之间共享数据的最佳方式
- const auto & 和 auto & if reference 对象之间的区别是 const
- C++ if 语句将条件设置为 true 和循环中的 OR-ing 条件之间的行为差异
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- 编译器之间在丢弃的 if constexpr(false) 语句中实例化模板的行为不一致
- IF(INTVAR)和IF(intvar!= 0)之间是否存在区别
- if(NULL==指针)和if(指针==NULL)之间有什么区别
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- 出现错误时在if/else块之间切换
- 如何在C++中的正整数和负整数之间计算IF语句中的bool
- c++中if(指针)与if(指针!=NULL)之间的差异,cpplint问题
- 如何使用介于 2 个数字之间的数字使" if "陈述为真?C++