当我运行这个PHP(5.4.31,在32位windows xp上运行)代码时,我得到了我期望的结果:
.typewriter h1 {
overflow: hidden; /* Ensures the content is not revealed until the animation */
border-right: .15em solid orange; /* The typwriter cursor */
white-space: nowrap; /* Keeps the content on a single line */
margin: 0 auto; /* Gives that scrolling effect as the typing happens */
letter-spacing: .15em; /* Adjust as needed */
animation:
typing 3.5s steps(40, end),
blink-caret .75s step-end infinite;
}
body {
background: #333;
color: #fff;
font-family: monospace;
padding-top: 5em;
display: flex;
justify-content: center;
}
/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
overflow: hidden; /* Ensures the content is not revealed until the animation */
border-right: .15em solid orange; /* The typwriter cursor */
white-space: nowrap; /* Keeps the content on a single line */
margin: 0 auto; /* Gives that scrolling effect as the typing happens */
letter-spacing: .15em; /* Adjust as needed */
animation:
typing 3.5s steps(40, end),
blink-caret .75s step-end infinite;
}
/* The typing effect */
@keyframes typing {
from { width: 0 }
to { width: 100% }
}
/* The typewriter cursor effect */
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: blue; }
}
但如果我将小数点移动过来:
<div class="typewriter">
<h1>The cat and the hat.</h1>
</div>
尽管有for($i = 0; $i <= 10; $i = $i + 0.5)
echo $i .' ';
子句,但循环以0.95而不是1退出。
我知道浮点数有一种不精确的性质,但这似乎有点极端。
答案 0 :(得分:3)
这是如何表示浮点数的问题。为了解决这个问题,我建议更改代码以使用整数索引,
for($i = 0; $i <= 100; $i = $i + 5)
echo ($i/100) .' ';
这样你只需将索引缩放100倍,然后在循环内将i
除以100,得到你想要的浮点数。
答案 1 :(得分:1)
我怀疑这是您在问题中隐含的浮点精度问题。
例如,尝试以下javascript:
for($i = 0; $i <= 1; $i = $i + 0.5) { console.log($i + " "); }
VS
for($i = 0; $i <= 1; $i = $i + 0.05) { console.log($i + " "); }
您将看到相同的行为,并且您会看到浮动点不精确地抬头:
0
VM4901:1 0.05
VM4901:1 0.1
VM4901:1 0.15000000000000002
VM4901:1 0.2
VM4901:1 0.25
VM4901:1 0.3
VM4901:1 0.35
VM4901:1 0.39999999999999997
VM4901:1 0.44999999999999996
VM4901:1 0.49999999999999994
VM4901:1 0.5499999999999999
VM4901:1 0.6
VM4901:1 0.65
VM4901:1 0.7000000000000001
VM4901:1 0.7500000000000001
VM4901:1 0.8000000000000002
VM4901:1 0.8500000000000002
VM4901:1 0.9000000000000002
VM4901:1 0.9500000000000003
如果你需要像这样在浮点上精确迭代,可以在迭代时考虑乘法,舍入和转换为整数。
答案 2 :(得分:-1)
我意识到还有一个简单的解决方案,使用round()
:
for($i = 0; $i <= 1; $i = round($i + 0.05,2) )
echo $i .' ';
其他答案更好。谢谢!我应该阅读有关浮动的PHP手册页。