Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have a problem to divide the money value to "0".
i build accounting software, with a shrinking asset.
example, i have a value 1000000.
i would divide it into 3.
1000000 / 3 = 333333,33333333333333333333333
the question is, i would to do this:
step 1 :1000000 - 333333,33333333333333333333333 =
666666,66666666666666666666667
step 2 :666666,66666666666666666666667 -
333333,33333333333333333333333 = 333333,33333333333333333333334
step 3 :333333,33333333333333333333334 -
333333,33333333333333333333333 =
0,00000000000000000000001
example code
decimal value = 100;
int divider = 3;
decimal x = value / divider;
for (int i = 0; i < divider; i++)
{
value = value - x;
}
the result, value = 0,000000000000000000000000001 .
yeah, that is a problem.
that a money value, i would divide to zero.
I've tried using math method like a "math.floor" at each step (on loop).
the result value is -2.
i know i can using "math.floor" method for the final result. but i don't, because i want to do step to step (on loop.)
what should i do?
thanks
You should consider multiplying your 1/3 by 1, 2, or 3 instead of subtracting the previous number. Something like this should work:
var originalAmount = 1000000d;
var thirdOfOriginal = originalAmount / 3;
Console.WriteLine("Original number ... {0}", originalAmount);
Console.WriteLine("Original - 1/3 .... {0}", (originalAmount - (thirdOfOriginal * 1)));
Console.WriteLine("Original - 2/3 .... {0}", (originalAmount - (thirdOfOriginal * 2)));
Console.WriteLine("Original - 3/3 .... {0}", (originalAmount - (thirdOfOriginal * 3)));
// Output
// Original number ... 1000000
// Original - 1/3 .... 666666.666666667
// Original - 2/3 .... 333333.333333333
// Original - 3/3 .... 0
This could be written more generically as:
private static List<decimal> GetAmounts(decimal originalNumber, int numberOfDivisions)
{
var amounts = new List<decimal>();
if (numberOfDivisions > 0)
{
var fraction = originalNumber / numberOfDivisions;
for (int i = 1; i <= numberOfDivisions; i++)
{
amounts.Add(originalNumber - (fraction * i));
}
}
return amounts;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Does it have a shorter way than doing something like this:
int[] Summe = new int[6];
Summe[0] = 1;
Summe[1] = 2;
Summe[2] = 3;
Summe[3] = 4;
Summe[4] = 5;
Summe[5] = 6;
Console.WriteLine(Summe[0] + Summe[1] + Summe[2] + Summe[3] + Summe[4] + Summe[5]);
Console.ReadKey();
Using the Enumerable.Sum() method which computes the sum of a sequence of numeric values and Enumerable.Take() which returns a specified number of contiguous elements from the start of a sequence.
Console.WriteLine(Summe.Take(10).Sum());
OR from high school
// sum of integers from 1 to n
int SumNaturalNumbers(int n)
{
return n * (n + 1) / 2;
}
Formula for the general algebraic series starting from a and difference between terms d (Arithmetic progression and series)
sum = n / 2 * (2 * a + (n - 1) * d)
I think using a foreach loop may be helpful here, since you're dealing with an array. Also, you can define your array on one line.
int[] Summe = { 1, 2, 3, 4, 5, 6 };
int total = 0;
foreach (int number in Summe)
{
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
You can simplify this process by simply putting this operation into a while loop.
int i = 0; // tell your program what 'i' should be upon first running the code
while (i < 10) // if 'i' is less than 10, run this block of code. You can change 10 to anything you want
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
This will print each number individually, but you want to calculate the sum of every number, so you could do something like this:
{
public static void Main()
{
int j, sum = 0;
Console.Write("\n\n");
Console.Write("Find the sum of first 10 natural numbers:\n");
Console.Write("----------------------------------------------");
Console.Write("\n\n");
Console.Write("The first 10 natural number are :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j; // add the previous number to the current one
Console.Write("{0} ",j);
}
Console.Write("\nThe Sum is : {0}\n", sum);
}
}
The above code prints the sum of the first 10 natural numbers. I added some additional lines simply to make the program more legible. Again, you can change the number 10 to whatever number you want.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to make output : 1 1 2 6 3 11 4 16 5 21. when i input start value = 1, and end value = 5
my code :
Console.Write("input start value : ");
start = int.Parse(Console.ReadLine());
Console.Write("input end value : ");
end = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = start; i <= end; i++)
{
Console.WriteLine(i);
for (int j = i; j <= end; j++)
{
int z = 1;
if (start != j)
{
z++;
Console.WriteLine((j * j) + z);
}
else
{
Console.WriteLine(start + " this j start value");
}
}
}
So it's not entirely clear to me if the 5 is used both as an end value for the 1,2,3,4,5 as well as a difference value for the 1,6,11,16,21 but I'll assume yes. Here's an algorithm for you to implement (this looks like homework, so think of this as a tip - you'll get more out of doing the coding yourself but this is how you should approach any coding exercise: write out the algorithm in the language you think in then translate it to c#)
ask the user for a start value and convert to int
ask the user for an end value and convert to int
work out a variable called n which is end minus start
make a for loop starting at x = 0, running while x is less than or equal to n ; incrementing x by 1
print out startValue plus x
print out startValue plus (endValue times x)
loop around
For a start and end of 1 and 5, the loop runs from 0 to 4. The first time the loop runs, x is 0, startValue is 1, so a 1+0 and a 1+(5*0) are printed - both 1. This continues up to the end value where x is 4, 4+1 is printed - which is 5 - and 1+(4*5) is printed - which is 21
As #dxiv has posted in the comments, the pattern for the set of numbers is to combine 1,2,3,4,5 and 1,6,11,16,21. The pattern that I see is that the gap between the second set of numbers is equal to the ending number.
We can define a function which generates these numbers:
IEnumerable<int> GetNumbers(int start, int end)
{
for (int number = start; number <= end; number++)
{
yield return number;
yield return start + ((number - 1) * end);
}
}
And can output the results like:
int start = 1;
int end = 5;
Console.WriteLine(string.Join(' ', GetNumbers(start, end)));
Output
1 1 2 6 3 11 4 16 5 21
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I am trying to generate a sequence of N numbers where the sum will be S.
Right now I am doing this:
float baseamount = (float)(amount / norders) * 0.8f;
float secondamount = amount / norders;
then generate N random numbers between these 2 numbers.
However this generates a pretty uniform range of numbers whereas I want a bit more randomized, for example, instead of (sum = 200, n = 10):
16.92321 17.49378 16.26426 16.03404 16.12497 17.53131 18.10094 16.86982 17.0831 16.06921
I prefer:
12.345 17.4534 19.3542342 11.345345 18.4325235 14.4353245 ...
What's the best way to approach this?
This method creates n values that have a mean of sum/count varying by a defined value. The constant calculation of minand max in each cycle achieves that the last value (which in this case actually is the first of the array), does not stick out so much. Though, its still not perfect, especially when you have a small mean value and a large variance. But maybe this gives you a start.
public static IEnumerable<double> GetValues(int count, double sum, double variance)
{
var rnd = new Random();
var values = new double[count];
var remainingSum = sum;
for (int i = count-1; i > 0; i--)
{
var min = (int)(remainingSum / (i+1) - variance / 2) * 1000;
var max = (int)(remainingSum / (i+1) + variance / 2) * 1000;
var rndVal = rnd.Next(min, max) / 1000.0;
values[i] = rndVal;
remainingSum -= rndVal;
}
values[0] = remainingSum;
return values;
}
Generate (n-1) random numbers not greater than sum/n and keep track of the partial sum (let's call it PS).
Then, your last number is (sum - PS).
Hope this helps.
EDIT: of course you'll have the last number exceptionally greater than all the previous ones. I'll investigate a more mathematical-oriented solution to this problem (or at least I'll try to). Meanwhile a "fix" has occurred to me:
(Let's call the random sequence a0,...,an).
Generate the sequence as described above
Generate a random number rd in the interval [0;k] (you need to choose k).
an-=rd
For each ai: ai+=rd/(n-1).
If I did everything well, the sum should not have changed and you have a more uniform sequence. k must be chosen by you depending on how "uniform" you want your sequence to be.
static Random random = new Random();
float[] Generate(float sum, int n, float minLimit)
{
float max = sum - minLimit * n;
float[] arr = new float[n];
for (int i = 0; i < n - 1; i++)
{
arr[i] = (float)random.NextDouble() * max;
}
arr[n - 1] = max;
Array.Sort(arr);
for (int i = n - 1; i > 0; i--)
{
arr[i] = arr[i] - arr[i - 1] + minLimit;
}
arr[0] += minLimit;
return arr;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
if doublevalue = 124.75 then it shoud be rounded to 125.00
if doublevalue = 124.25 then it shoud be rounded to 124.50
in short after decimal point digit greater than 50 must rounded to 100 and less than 50 should rounded to 50
please help me get this type of code
Simply do the following:
Math.Ceiling(YourValue * 2)/2
Explanation
Suppose your number can be written as X + Y, where X is the integer part and Y is the fractional part. Multiplying it with 2 will make it 2X + 2Y, where 2X will be an even number, double of the integer part. For Y, there are two cases:
If Y >= 0.5, 2Y will be equal to 1 + Z (where 0 <= Z < 1), thus the entire number will be 2X + 1 + Z.
If Y < 0.5, 2Y will be equal to Z (where 0 <= Z < 1), thus the entire number will be 2X + Z.
Doing Math.Ceiling() in the first case will return 2X + 2 and dividing it by 2 will return X + 1, which is the nearest higher integer, (3.7 will become 4).
Doing Math.Ceiling() in the second case will return 2X + 1 and dividing it by 2 will return X + 0.5, or X.5 , (3.3 will become 3.5).
your conditions are not clear from your question, but the principle is to isolate the digits after the decimal point and that decide what to do:
private static double GetFixedNumber(double n)
{
var x = n - Math.Floor(n);
double result = 0;
if (x >= 0.75)
{
result = Math.Floor(n) + 1;
}
else if (x >= 0.25)
{
result = Math.Floor(n) + 0.5;
}
else
{
result = Math.Floor(n);
}
return result;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine( RoundUp(124.25, 2));
}
public static double RoundUp(double input, int places)
{
double multiplier = input*2;
double numberround = Math.Round(multiplier, MidpointRounding.AwayFromZero)/2;
return numberround;
}
}
}
Or compute it yourself:
// flipped the decision around - else it is kindof the same.
static double WorksAsWell(double input)
{
var floored = Math.Floor(input);
if (floored == input) // special case so exact 127. stays that way
return floored;
if (input - floored >= 0.5)
return floored+1;
return floored+0.5;
}
static double RoundToHalfesOrFulls(double input)
{
int asInt = (int)Math.Floor(input);
double remainder = input-asInt;
if(remainder < 0.5)
return asInt+0.5;
return asInt+1.0;
}
public static void Main()
{
for(int i= 12700; i < 12800; i+=5)
System.Console.WriteLine(string.Format("{0} = {1}",i/100.0, RoundToHalfesOrFulls(i/100.0)));
}
}
Output: (RoundToHalfesOrFulls)
127 = 127
127.05 = 127
127.1 = 127
127.15 = 127
127.2 = 127
127.25 = 127
127.3 = 127
127.35 = 127
127.4 = 127
127.45 = 127
127.5 = 127.5
127.55 = 127.5
127.6 = 127.5
127.65 = 127.5
127.7 = 127.5
127.75 = 127.5
127.8 = 127.5
127.85 = 127.5
127.9 = 127.5
127.95 = 127.5
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Having a List of numbers, I want to take every n(e.g. 5 , 10 , etc.) element, compute their average and put the average in a new list. As an example lets assume we have the following list:
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8
Now we compute the average every 2 elements and we will get the following list as output:
1.5 , 3.5 , 5.5 , 7.5
How can I do that?
You could use a for-loop and Enumerable.Average:
var averages = new List<double>();
for (int i = 0; i < ints.Length; i += 2)
{
int thisInt = ints[i];
int nextInt = i == ints.Length - 1 ? thisInt : ints[i + 1];
averages.Add(new[] { thisInt, nextInt }.Average());
}
Here's a dynamic approach that works with any length:
int take = 2;
for (int i = 0; i < ints.Length; i += take)
{
if(i + take >= ints.Length)
take = ints.Length - i;
int[] subArray = new int[take];
Array.Copy(ints, i, subArray, 0, take);
averages.Add(subArray.Average());
}
This problem is just testing your use of iteration and the modulus operator. Modulus gives you the remainder of division, you can use it to check whether or not the current number should be included in the average as you iterate the array. Here is a sample method;
public float nthsAverage(int n, int[] numbers)
{
// quick check to avoid a divide by 0 error
if (numbers.Length == 0)
return 0;
int sum = 0;
int count = 0;
for (int i = 0; i < numbers.Length; i++)
{
// might want i+1 here instead to compensate for array being 0 indexed, ie 9th number is at the 8th index
if (i % n == 0)
{
sum = sum + numbers[i];
count++;
}
}
return (float)sum / count;
}
public List<double> Average(List<double> number, int nElement)
{
var currentElement = 0;
var currentSum = 0.0;
var newList = new List<double>();
foreach (var item in number)
{
currentSum += item;
currentElement++;
if(currentElement == nElement)
{
newList.Add(currentSum / nElement);
currentElement = 0;
currentSum = 0.0;
}
}
// Maybe the array element count is not the same to the asked, so average the last sum. You can remove this condition if you want
if(currentElement > 0)
{
newList.Add(currentSum / currentElement);
}
return newList;
}