![]() ![]() (As a refresher, 21 divided by 7 is 3, and there are two remaining to get up to 23. So it is important to remember that in C#, % does not mean "percent", it means "get the remainder of". The sign for this operator is the percent sign ("%"). This operator only gives you back the remainder, not the division result. This operator is called the "modulus" operator (or "mod" for short). The Modulus Operatorĭo you remember in elementary school, not too long after you first learned division, how you always did things like: "23 divided by 7 is 3 remainder 2"? Well, in programming, calculating the remainder has its own operator, just like division. There's a little more going on here than that, but we'll discuss it more in a few tutorials. If you run this code, you will see that the result is the computer prints out, "The area of the circle is 50.26548". It knows that you can't "add" strings in a mathematical sense, but there is an intelligent way of handling it: to concatenate the text together so that one follows the other. Notice, too, that we've been able to use the '+' operator with strings (text). We then print out the result for the user. ![]() In the above code snippet, we have variables for the radius of a circle, the value of the number PI, and the area, which we calculate using a standard formula from geometry class. WriteLine ( " The area of the circle is " + area ) Note how using '+' with a string (text) "concatenates" the number on the end of the text. The formula for the area of a circle is pi * r ^ 2 float radius = 4 įloat pi = 3.1415926536 f // The 'f' at the end makes it treat it as a float instead of a double. The following code adds the numbers '3' and '4' and stores the result in the variable called a: Let's start with a simple math problem that you probably did in second grade. Addition, Subtraction, Multiplication, and Divisionĭoing the basic operations of addition, subtraction, multiplication, and division should be pretty straightforward, especially if you have done other programming before. In this tutorial, we'll cover how to do some basic arithmetic in C#, starting with addition and subtraction, and move up through multiplication and division, a new operation called the modulus operator, positive and negative numbers, order of operations, and conclude with some compound assignment operators, which do math and assign a value all at once. In fact, it is basically all they can do. This math is all pretty easy-the kind of stuff you learned in elementary school. With a basic understanding of variables behind us, we're ready to get into some deeper material: math.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |