给定浮点数N ,任务是检查N的值是否等于整数。如果发现是真的,则打印“是” 。否则,打印“否” 。
例子:
Input: N = 1.5
Output: NO
Input: N = 1.0
Output: YES
方法:想法是使用类型转换的概念。请按照以下步骤解决问题:
- 初始化一个变量,例如X ,以存储N的整数值。
- 将N的float值转换为整数,并将其存储在X中。
- 最后,检查(N – X)是否大于0 。如果发现是真的,则打印“否” 。
- 否则,打印“是” 。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to check if N is
// equivalent to an integer
bool isInteger(double N)
{
// Convert float value
// of N to integer
int X = N;
double temp2 = N - X;
// If N is not equivalent
// to any integer
if (temp2 > 0) {
return false;
}
return true;
}
// Driver Code
int main()
{
double N = 1.5;
if (isInteger(N)) {
cout << "YES";
}
else {
cout << "NO";
}
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// Function to check if N is
// equivalent to an integer
static boolean isInteger(double N)
{
// Convert float value
// of N to integer
int X = (int)N;
double temp2 = N - X;
// If N is not equivalent
// to any integer
if (temp2 > 0)
{
return false;
}
return true;
}
// Driver code
public static void main(String[] args)
{
double N = 1.5;
if (isInteger(N))
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
// This code is contributed by susmitakundugoaldanga
Python3
# Python3 program to implement
# the above approach
# Function to check if N is
# equivalent to an integer
def isInteger(N):
# Convert float value
# of N to integer
X = int(N)
temp2 = N - X
# If N is not equivalent
# to any integer
if (temp2 > 0):
return False
return True
# Driver Code
if __name__ == '__main__':
N = 1.5
if (isInteger(N)):
print("YES")
else:
print("NO")
# This code is contributed by mohit kumar 29
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to check if N is
// equivalent to an integer
static bool isint(double N)
{
// Convert float value
// of N to integer
int X = (int)N;
double temp2 = N - X;
// If N is not equivalent
// to any integer
if (temp2 > 0)
{
return false;
}
return true;
}
// Driver code
public static void Main(String[] args)
{
double N = 1.5;
if (isint(N))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
// This code is contributed by 29AjayKumar
输出:
NO
时间复杂度: O(1)
辅助空间: O(1)