Hi I am currently teaching myself C# using different books and online solutions, there is one exercise that i cant really get my head around. I had to divide a number by another number in C# using iteration and subtraction but the remainder had to be displayed at the end. I figured out that I could use a while loop to keep dividing one number by the other (lets say 400 / 18) but how to display the decimal at the end from the int number was the part I could not get my head around. Any help would be greatly appriciated :)
-
Please post the current stand of your code – Andres L May 16 '13 at 12:27
-
Divide two numbers involving iteration, you need to show up the code you are stuck with as of now the question is vague – V4Vendetta May 16 '13 at 12:27
2 Answers
So let's think about this outside the C# language. Because this is really just a math problem to solve.
If you've got 400/18, and you are going to use iteration and subtraction, all you are doing is saying "how many times can I subtract 18 from 400?", right?
So that's going to look something like this:
remainder = 400
value = 18
while (remainder > value)
remainder = remainder - value
Once you exit that while loop, you've got your remainder.
You could use the modulus operator "%" to solve this in one step but based on what you wrote, this is what you would do.
The remainder you've got is can be expressed as so:
double theDecimalValue = (double)remainder/value;
Assuming you were dealing with integers, you'd just cast the remainder value to avoid the truncating integer division that will take place otherwise.

- 31,265
- 10
- 100
- 164
-
-
Ahh so my only real problem was the fact that i didnt cast the finishing variable as a double so that it would display the remainder! Thanks for this it is much appriciated, alot simpler than I thought :) – user2311703 May 16 '13 at 13:53
if you need the remainder the easy and right way is
int reminder = 400%18;
if you HAVE TO using a loop you have to :
- check if number is less than the divisor or whatever it's called
2a.if yes exit from the loop and show the number
2b if not remove divisor from number and go on next iteration

- 2,315
- 2
- 24
- 30