Csharp/CSharp Tutorial/Statement/Do While — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:20, 26 мая 2010
Содержание
Display the digits of an integer in reverse order with do while loop
using System;
class MainClass {
public static void Main() {
int num;
int nextdigit;
num = 198;
Console.WriteLine("Number: " + num);
Console.Write("Number in reverse order: ");
do {
nextdigit = num % 10;
Console.Write(nextdigit);
num = num / 10;
} while(num > 0);
Console.WriteLine();
}
}
Number: 198 Number in reverse order: 891
Do while loop
A do-while loop will always execute at least once.
The general form of the do-while loop is
do {
statements;
} while(condition);
Do / while loop with a console read
using System;
using System.IO;
class MainClass
{
public static void Main(string[] args)
{
string ans;
do
{
Console.Write("Are you done? [yes] [no] : ");
ans = Console.ReadLine();
}while(ans != "yes");
}
}
Are you done? [yes] [no] : yes
Use the do while statement to implement Newton"s method for finding the square root of a number
using System;
public class MainClass {
public static void Main( ) {
double epsilon = 1.0e-9;
double guess = 11.0;
double result = 0.0;
double value = 2;
result = ((value / guess) + guess) / 2;
do {
Console.WriteLine( "Guess Value = {0}", guess );
Console.WriteLine( "Result Value = {0}", result );
guess = result;
result = ((value / guess) + guess) / 2;
} while( Math.Abs(result - guess) > epsilon );
Console.WriteLine("The approx sqrt of {0} is {1}", value, result );
}
}
Guess Value = 11 Result Value = 5.59090909090909 Guess Value = 5.59090909090909 Result Value = 2.97431633407243 Guess Value = 2.97431633407243 Result Value = 1.82336988350512 Guess Value = 1.82336988350512 Result Value = 1.46012001740362 Guess Value = 1.46012001740362 Result Value = 1.41493521627426 Guess Value = 1.41493521627426 Result Value = 1.41421374640426 Guess Value = 1.41421374640426 Result Value = 1.41421356237311 The approx sqrt of 2 is 1.41421356237309