栈
0.1
数据结构_第3章
ch3_2.cc
Go to the documentation of this file.
1
12
#include "
Stack.hh
"
13
#include <cmath>
14
#include <iostream>
15
#include <string>
16
22
static
void
prnUIntInBin
(
unsigned
long
decUi = 0);
23
31
static
void
prnPDecInBin
(
double
pDec = 0.0,
unsigned
int
errP = 20);
32
43
int
main
(
int
argc,
char
const
*argv[])
44
{
45
if
(argc > 1)
46
{
47
auto
decNum = std::stod(argv[1], 0);
48
if
(decNum < 0)
49
throw
(std::string{
"argv[1] should be a non-negative decimal number!"
});
50
51
auto
IntPart = floor(decNum);
//整数部分
52
prnUIntInBin
(IntPart);
53
prnPDecInBin
(decNum - IntPart);
54
std::cout << std::endl;
55
return
0;
56
}
57
58
double
decNum{0.0};
59
60
// Get legal input
61
do
62
{
63
std::cout <<
"Please input a non-negative decimal number: "
<< std::endl;
64
std::cin >> decNum;
65
if
(!std::cin.fail() && decNum >= 0)
66
break
;
67
68
std::cin.clear();
69
std::cin.sync();
70
}
while
(
true
);
71
72
auto
IntPart = floor(decNum);
73
prnUIntInBin
(IntPart);
74
prnPDecInBin
(decNum - IntPart);
75
std::cout << std::endl;
76
77
return
0;
78
}
79
80
void
prnUIntInBin
(
unsigned
long
decUi)
81
{
82
Stack::linkStack<char>
lst{};
83
do
84
{
85
lst.
push
(decUi % 2 +
'0'
);
86
decUi /= 2;
87
}
while
(decUi);
88
89
std::cout <<
"Binary representation:\n"
;
90
while
(!lst.isEmpty())
91
std::cout << lst.pop();
92
}
93
94
void
prnPDecInBin
(
double
pDec,
unsigned
int
errP)
95
{
96
std::cout <<
'.'
;
97
98
if
(pDec >= 1)
99
throw
(std::string{
"Not a pure decimal!"
});
100
101
do
102
{
103
pDec *= 2;
104
if
(pDec >= 1)
105
{
106
std::cout <<
'1'
;
107
--pDec;
108
--errP;
109
continue
;
110
}
111
std::cout <<
'0'
;
112
}
while
(errP && pDec);
113
}
Stack::linkStack::push
virtual void push(const T &elem)
Definition:
linkStack.hpp:76
Stack::linkStack
Definition:
linkStack.hpp:21
prnUIntInBin
static void prnUIntInBin(unsigned long decUi=0)
将十进制非负整数以其二进制形式打印
Definition:
ch3_2.cc:80
prnPDecInBin
static void prnPDecInBin(double pDec=0.0, unsigned int errP=20)
将(非负)十进制纯小数以其二进制形式打印
Definition:
ch3_2.cc:94
main
int main(int argc, char const *argv[])
将非负十进制实数以其二进制形式打印
Definition:
ch3_2.cc:43
Stack.hh
栈的抽象类
src
ch3_2.cc
Generated on Mon Jul 6 2020 21:04:43 for 栈 by
1.8.17