如何用c語言判斷一個數為小數?
#include
int main(void)
{
double no;
printf(“請輸入一個數字;”);scanf(“%lf”,&no);
if((int)no == no)
puts(“這個數不為小數”);
else
puts(“這個數為小數”);
return 0;
}
用 strchr()
讀入字串,有小數點的是小數。
利用C語言的強制轉換來壓縮資料做判斷,不考慮溢位的情況下:
bool
isInteger
(
double
x
)
{
int
truncated
=
(
int
)
x
;
return
(
x
==
truncated
);
}
不是整數就是小數了唄
我看有人不太理解,題主的問題是
要判斷一個數是不是小數,而不是資料型別
。最直觀的理解:
2。01,我認為是小數
2。00,我就認為不是小數
以上兩點是這個函式的最基本前提條件,所以,在
int truncated = (int)x;
之後,
truncated
裡面保留的只有小數點前面的部分,所以如果壓縮後依然相等,就說明壓縮前
x
小數點後面也都是0。
int
NumType
(
char
*
Str
)
{
// 判斷一個字串表示整數 / 小數 / 其他內容;
if
(
NULL
==
Str
)
{
return
(
-
1
);
}
bool
dot
=
false
;
// 小數點;
char
*
p
=
Str
;
char
Ch
=
*
p
;
if
(
‘-’
==
Ch
||
‘+’
==
Ch
)
{
++
p
;
// 正負號;
}
for
(;
Ch
=
*
p
;
++
p
)
{
if
(
‘。’
==
Ch
)
{
if
(
dot
)
{
return
(
-
1
);
}
dot
=
true
;
}
else
if
(
‘9’
<
Ch
||
‘0’
>
Ch
)
{
return
(
-
1
);
}
}
return
(
dot
?
1
:
0
);
}
#include
#include
#include
“Smile。h”
int
main
(
int
argc
,
char
**
argv
)
{
const
int
Len
=
32
;
char
*
Str
=
(
char
*
)
calloc
(
Len
,
sizeof
(
char
));
printf
(
“每次輸入一串數字, 判斷屬於整數/小數/其他型別; 輸入Q退出。
\n
”
);
do
{
scanf
(
“%s”
,
Str
);
switch
(
NumType
(
Str
))
{
case
(
0
)
:
{
printf
(
“整數。
\n\n
”
);
break
;
}
case
(
1
)
:
{
printf
(
“小數。
\n\n
”
);
break
;
}
default
:
{
printf
(
“輸入錯誤。
\n\n
”
);
break
;
}
}
}
while
(
‘Q’
!=
*
Str
);
free
(
Str
);
return
0
;
}
這樣行不行呀?