1.2 Variables and Arithmetic Expressions
/*Print Fahrenheit-Celsius table: for fahr =0, 20, ... ,300*/ void ConvertFahrenheittoCelsius() { int Fahr, Celsius; int lower, higher, step; lower = 0; higher = 300; step = 20; while (lower < higher) { Fahr = lower; Celsius = 5 * (Fahr - 32) / 9; printf("\t%d\t%d\n", Fahr, Celsius); lower = lower + step; }
namespace ConsoleApplication4 { class Program { static void Main(string[] args) { float Fahr, Celsius; int lower, higher, step; lower = 0; higher = 300; step = 20; Fahr = lower; while (Fahr < higher) { Celsius = (float)((5.0 / 9.0)*(Fahr - 32.0));
Console.WriteLine("{0}, \t {1}", Fahr, Celsius); Fahr = Fahr + step; } Console.ReadLine(); } } }
#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { float Fahr, Celsius; int lower, higher, step; lower = 0; higher = 300; step = 20; Fahr = lower; /* The int is converted to float before the operation is done.*/ while (Fahr <= higher) { Celsius = (5.0 / 9.0) * (Fahr - 32); printf("%3.0f %6.1f \n", Fahr, Celsius); Fahr = Fahr + step; } return 0; }
The reason for multiplying by 5 and then dividing by 9 instead of just multiplying by 5/9 is that in C,as in many other languages,integer division truncates: any fractional part is discarded.
Printf is a general-purpose output formatting function, and it is just a useful function from the standard library of functions that are normally accessible to C programs.
In C Sharp,double cannot implicitly be converted to float.
The printf conversion specification %3.0f says that a floating-point number is to be printed at least three
characters wide, with no decimal point and no fraction digits.