Commit 75a37b8e authored by Tapio Mäntysalo's avatar Tapio Mäntysalo
Browse files

Task 2 now works.

parent d29ff637
......@@ -10,6 +10,40 @@
</head>
<body>
<div class="alert alert-primary" role="alert">
Excercises of week 1, Tapio Mäntysalo, 28.3.2020, FS2
</div>
<!-- Task 2 -->
<div class="container-md">
<div class="jumbotron">
<h1 class="display-4">Task 2</h1>
<p class="lead">Loops</p>
<hr class="my-4">
<p> It is a common practice to avoid using decimal numbers as loop counters because rounding errors can have
surprising effects. In this exercise we see one example of that. The task here is to simply count the
sum 0 + 0.1 + 0.2 + … + 0.9. It has been implemented as follows: <br>
<font face="courier">
&nbsp;let sum = 0; <br>
&nbsp;for(let i = 0; i != 1; i += 0.1) {<br>
&nbsp;&nbsp;&nbsp;&nbsp;sum += i;<br>
&nbsp;} <br>
&nbsp;alert(sum);<br>
</font>
The rationale is that after adding 0.1 ten times, the value of the loop counter is 1 and the
loop should
end. However, when the program is executed, it appears to never end. Fix the program so that
an infinite
loop is avoided and it gives the correct result.
</p>
<hr>
<p>
<button type="button" class="btn btn-primary" id="btn-task-2">Calculate</button>
</p>
<p id="card-task-2-result"></p>
</div>
</div>
<!-- Task 1 -->
<div class="container-md">
<div class="jumbotron">
......@@ -84,7 +118,8 @@
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<script src="task1.js"></script>
<script src="task2.js"></script>
<script src="task1.js"></script>
<script src="example.js"></script>
</body>
......
$("#card-task-2-result").text("");
// Show the result
$("#btn-task-2").click(function () {
let sum = getSum();
$("#card-task-2-result").text(`The result is ${sum}`);
});
function getSum() {
let sum = 0;
for (let i = 0; i < 10; i++) {
sum += i / 10;
}
return sum;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment