Проверить, целое число или нет
С использованием цикла While написать программу :Дано целое число N. Проверить является ли число N числом Фибоначчи
Помогите пожалуйста 1)с использованием цикла While и без масивов написать программу которая.
Как проверить, целое ли число?
Есть идея перевести в стринг и искать точку или перевести в инт и сравнить
Целое или нет?
В с# мне нужно проверить является это число целым или нет. Помогите написать програмку на лёгком.
Дано целое число N. Найти наименьшее целое положительное число K, при котором выполняется неравенство 3^k > N.
Используя цикл while Дано целое число N. Найти наименьшее целое положительное число K, при котором.
Как определить, целое ли число?
![]()
Давно C++ не использовал, но на сколько я помню такие вещи делаются через оператор привидения типов:
Все другие привидения — это что-то унаследованное от С . В С++ для каждого случая есть свой оператор.
Для проверки встроенных типов данный подход не подойдет. В различных компиляторах есть макросы, например, __typeof__ . Они специфичны для конкретного компилятора.
C++ Поддерживает урезанный RTTI. Возможно использовать только языковые возможности C++ , посмотрите на этот код:
![]()
Лучше всегда использовать double (float только для хранения в больших массивах).
Для этого надо подключить math.h.
Некоторые могут возразить, что сравнивать числа с плавающей запятой на равенство неправильно. Но если бы это было неправильно всегда, компилятор бы такое в принципе не позволял. В данном случае целые числа могут быть представлены точно в double. Операции сложения, вычитания и умножения для целых чисел также дадут целые числа, так как не вносят погрешностей округления. Для чисел, заданных вручную или полученных таким способом, проверка выше сработает корректно. Если всё же нужно проверить, что число целое в пределах некоторой погрешности eps (например 0.000001), можно использовать следующую проверку:
Или если в используемой версии стандартной библиотеки доступна функция round:
Эти два варианта используют округление к ближайшему целому, чтобы разность между этим и исходным числом была в интервале (-0.5; 0.5], а не [0; 1), как в случае округления к меньшему.
Как проверить что число целое c
Hello, imho the best way is using truncate or round:
- Edited by Miguel Fernández Corral Wednesday, October 10, 2012 4:32 PM
- Proposed as answer by Dan Randolph Thursday, October 11, 2012 3:27 AM
- Marked as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:07 AM
- Unmarked as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:07 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:20 AM
I hope this helps.
Please mark this post as answer if it solved your problem. Happy Programming!
- Edited by Adavesh Wednesday, October 10, 2012 5:18 PM
- Proposed as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:15 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:20 AM
Hi, the above codes works.
but if you use this extensively you may create a method that do this operation:
Now you can use this method as follows:
- Proposed as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:16 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:19 AM
All replies
Dear All,
In C#, how to check if a double is integer number?
To the numeric type itself, an integer can NEVER be a double.
But if you wanna check whether they equal to each other, just do this:
Notice it that u can never use a cast convert to compare because the precious number will be lost, and u have to use format to format the number into a form of united formation to compare with.
- Edited by ThankfulHeart Wednesday, October 10, 2012 4:41 AM
Try this as well:
- Proposed as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:16 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:19 AM
I’m afraid you cannot use that to check, because just as what I said above, if your double number has been cut into integer, this will cause the problem that only the "integer" part is preserved:
In fact it should output false……But after the experinment it outputs True.
Kindly corrent me if you conflict with me;)
——No need of conversion at all!
Hi, the above codes works.
but if you use this extensively you may create a method that do this operation:
Now you can use this method as follows:
- Proposed as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:16 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:19 AM
Why do you think it should output false?
Hello, imho the best way is using truncate or round:
- Edited by Miguel Fernández Corral Wednesday, October 10, 2012 4:32 PM
- Proposed as answer by Dan Randolph Thursday, October 11, 2012 3:27 AM
- Marked as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:07 AM
- Unmarked as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:07 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:20 AM
I hope this helps.
Please mark this post as answer if it solved your problem. Happy Programming!
- Edited by Adavesh Wednesday, October 10, 2012 5:18 PM
- Proposed as answer by Lisa Zhu Moderator Thursday, October 11, 2012 6:15 AM
- Marked as answer by Lisa Zhu Moderator Tuesday, October 16, 2012 9:20 AM
In fact it should output false
Why do you think it should output false?
What do you expect the result?It should be False but it’s outputting True.
int num = 5 ;
double dnum = 5.6 ;
bool is_integer = unchecked ( num ==( int ) dnum );
Console . WriteLine ( is_integer );
I agree your 2nd method, and I think u can just do comparation with a double to an interger;)
- Edited by ThankfulHeart Thursday, October 11, 2012 1:23 AM
(int)5.6 being equal to 5, I expect 5==(int)5.6 to be true.
Why should it be false?
- Edited by Louis.fr Thursday, October 11, 2012 1:58 PM
Viorel’s method here is clearly the solution. To check if a floating point number is in fact an integer you simply need to see if it is equal to itself when truncated to an integer. This check is quick, easy, and performant.
Converting the value to a string and doing the comparison as 编程志愿者 suggested, or converting to a string and parsing as Adavesh suggested is excessively processor intensive.
@BGQQ the entire `if condition return true else return false` construct is redundant. The function doesn’t need to be any more than this:
@编程志愿者 (again) you do need to do the cast; it’s actually important that you do the cast. The idea here isn’t to compare some double with some int, the idea is to determine if a double is the same as itself as an int. The cast to int actually truncates the value; that’s important.
@Louis, He’s not saying that he thinks that statement should return false because it’s not true, he’s saying that 5.6 isn’t an integer value, so when comparing them *his code* should return false. It’s not that the code doesn’t do what either of you think it does, it’s simply that it doesn’t meet his requirements.
C++ Check If Input Is Int
Make sure to have a “G++” compiler for C++ language already configured and updated in your Ubuntu 20.04 Linux operating system. Let’s get started with the launch of the Ubuntu terminal using “Ctrl+Alt+T”. Create a C++ file using the simple “touch” instruction, and launch it within the “nano” editor of our Ubuntu 20.04 system as below.

Example 01:
We will start our C++ code within this file with the “iostream” header library and standard namespace, i.e., “Std” to utilize the code’s input and output statements, i.e., cout and cin. The C++ code execution always starts from its main() function.
Let’s discuss the main() function first. The main() function has been defined with “int” return type after the Boolean return type user-defined “check” function. The string “v” has been defined with no value. The “cout” statement is here to ask a user for a value, i.e., integer or string. The “cin” statement is here to save the value entered by a user in the variable “v”.
The “if-else” statement has been utilized to check whether the value entered by a user is an integer or not. Within the “if” part, we have been calling the Boolean “check()” function passing the variable “v” as an argument to it. The control goes to the “check” function. With the “check” function, the “for” loop has been used to iterate the value entered by a user for every letter/character until the end of the variable.
The “for” loop has the “if” statement again to use the “isdigit()” function on each character of value “v” entered by a user. The function “isdigit()” returns true or false in return. If it returns “true” it means a particular character is a number. Thus, the “return” statement will return “true” to the main() method. Else, it will return “false”.
The control came back to the main() function after the “for” loop ends. If the Boolean value returned by the “check” function is “true”, the “if” part cout statement will get executed. Else the “else” part cout statement will be executed.
Let’s use the g++ compiler to compile the code and run the “./a.out” command. The user inputs “hello” and get the message “value is not an integer”. The user inputted “140” as a value on the second execution and got the message “value is an integer”.

Example 02:
The isdigit() function can be utilized in another way within the code to check for the value if it is an integer or not. For this illustration, we will not be using the user-defined function check(). All the work will be managed within the main() function.
Within the main() method, we have initialized a variable “count” to “0” after the declaration of a string variable “v”. The cout statement has been used after that to ask the user for an input value. The cin statement is here to save the value entered by a user in a variable “v”. The “for” loop is used in the main() method as we did use it in the check() function before. It will iterate the value entered by a user up to its length.
The “if” statement is here to utilize the “isdigit” function. If the isdigit() value equals “true”, the count variable will be incremented. After the “For” loop, another “if” statement is here to check the “count” value and react according to that. If the cout value is 0 and equal to “length of the string”, it will display that the value is integer via the cout statement. Otherwise, the “else” statement will execute, showing that the value is not an integer.
On compilation and execution of this code, we have entered the “hell” value first and found that it’s not an integer value. We entered “42” as a value on the second execution, and it displays that the “42” is an integer value.

Example 03:
The function “find_first_not_of()” is a built-in function of C++. The variable “v” has been checked out through the “find_first_not_of()” function. It says if any character from value “v” is other than “0123456789” until the end of the variable, it will return “string::npos” which means “not matched”.
If the function return value equals “true” and no character string found so far i.e., the first cout statement will display that the value is an integer. Otherwise, if any of the values are matched, it will display that the value is not an integer i.e. might be a string.
On execution, the user added “c++” and the output shows the value is not an integer. On another execution, the user added 9808 and found that it is an integer value.

Conclusion:
This article covered some of the built-in utilities in C++ to check if the input value is some integer or not. Those utilized include the isdigit() function, count utility, Boolean values, and the find_first_not_of() function along with string::npos. Everything is well explained; thus, it will be quite easy to understand.
About the author
Kalsoom Bibi
Hello, I am a freelance writer and usually write for Linux and other technology related content