We can read values as a string, and convert them to real, as we did with integer numbers. We will now use Convert.ToDouble for double precision data, Convert.ToSingle for single precision (float) and Convert.ToDecimal for extra precision (decimal):
/*---------------------------*/
/* C# Example #27: */
/* example27.cs */
/* */
/* Real numbers (1) */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example27
{
public static void Main()
{
float firstNumber;
float secondNumber;
float sum;
Console.WriteLine("Enter the first number");
firstNumber = Convert.ToSingle(Console.ReadLine());
Console.WriteLine("Enter the second number");
secondNumber = Convert.ToSingle(Console.ReadLine());
sum = firstNumber + secondNumber;
Console.WriteLine("The sum of {0} and {1} is {2}",
firstNumber, secondNumber, sum);
}
}
Be careful when trying this program: although we must write the source of our program using the decimal point, such as 123.456, when the executable is run, we must use the correct separator for our country and regional configuration. For example, this can happen with the Spanish version of Windows XP:
Enter the first number
23,6
Enter the second number
34.2
The sum of 23,6 and 342 is 365,6
Suggested exercises:
Ø Create a program that displays the area of a circle, given its radius (pi * radius squared)
Ø Create a program to ask the user for a distance (in meters) and the time taken (as three numbers: hours, minutes, seconds), and display the speed, in meters per second, kilometers per hour and miles per hour (hint: 1 mile = 1609 meters).
Ø Find the solutions for a quadratic equation as y = Ax2 + Bx + C. Hint: the square root of a number x can be calculated with Math.Sqrt(x)
Ø Write a program to display the first 20 values for the function y = x2 – 1
Ø Create a program to "draw" the graphic for the equation y = (x-5)2, for x between 1 and 10. It must be displayed by drawing blank spaces followed by an asterisk. The amount of spaces will depend on the value of "y".
Ø Create a program to calculate an approximation for PI using the expression: pi/4 = 1/1 - 1/3 + 1/5 -1/7 + 1/9 - 1/11 + 1/13 … The user will indicate how many terms must be used, and the program will display all the results until that amount of terms.
No comments:
Post a Comment