As we have seen in earlier sections, you cannot store real values in int variables. Programs
will also get into trouble if they are expecting numeric input and they receive non-numeric (letters & symbols)
input. Fortunately Turing has predefined functions for converting from one type to another.
round
To convert from a real to an int you can use the round function. As the name suggests,
the real number will be rounded off to the nearest integer. Here are some examples:
round(3.5) = 4
round(-6) = -6
round(-11.99) = -12
round(-11.4999) = -11
To avoid crashing your program when reading numbers you can actually read them in as strings. That way it doesn't
matter what the person types. However, to do any calculations you will need to convert the string into an integer
or real value. Luckily there are predefined functions to do this for us.
strint
The STRing to INT function takes a string as a parameter and converts it into an integer, if possible.
There can be blanks in the front of the string but then only plus, minus or digits are allowed. If there
are other characters then the strint function causes an error. There is a function strintok which
can be used to determined if the string is safe to convert. Later, when we learn how to use the if
statement, we'll see how to use these two methods together to prevent the program from crashing. Here is an example:
var number : intvar s : stringput "Enter a number"
get s
number := strint(s)
put "Converted to an int it is ", number
put "Enter a number. If I say false that means you typed a"
put "letter and the program will crash after that"
get s
put strintok(s)
put "Now converted it is ", strint(s)
If the user typed some spaces and then +12345 for the first string and then 123abc for the second on this is the output
that would be produced.
Enter a number
+12345
Converted to an int it is 12345
Enter a number. If I say false that means you typed a
letter and the program will crash after that
123abc
false
Now converted it is
The program crashes on the last line because the string doesn't hold just an integer. You will get the error message
illegal character in string passed to "strint". Later we'll learn how to avoid that.
strreal
This function works the same as the previous one except that it will attempt to convert the string to a real.
There is also a function called strrealok, which is similar to the integer one that
checks if a string can be converted to a real.
Exercise 2.3
State the value of each expression.
round(3.499)
round(-6.9999)
round(-5.2)
strint("4243")
strint(" +5343")
round(1.49 + 0.1)
round(1.49) + 0.1
strintok("-1234")
strrealok("$3.32")
round(strreal("36178e-4"))
Write a program to read a number and round it to the neareast thousand.
Modify the program in question 2 so that it will round the the nearest hundredth.