Adding up total through a for loop - total always 0 - c#

I have a method to work out intervals from a file containing training data. It detects spikes and drops in power to figure out intervals and I'm developing a method to work out averages for each interval. Here is the method:
public void getIntervalData()
{
//Remove first drop anomaly
drops.Remove(0);
int intervalAltitude;
int intervalPower;
int intervalSpeed;
int altitudeAddUp = 0;
int powerAddUp = 0;
int speedAddUp = 0;
int counter = 0;
//Loop through to get all spikes and drops
for (int j = 0; j < spikes.Count(); j++)
{
int firstNumber = Convert.ToInt32(spikes[j]);
int secondNumber = Convert.ToInt32(drops[j]);
MessageBox.Show(firstNumber.ToString());
counter++;
//Difference to work out averages
int difference = secondNumber - firstNumber;
//Get seperate interval data (first number = spike, second number = drop)
for (int i = firstNumber; i < secondNumber; i++)
{
int altitudeNumber = altitudeList[i];
int powerNumber = powerList[i];
int speedNumber = Convert.ToInt32(speedList[i]);
//Add up data
altitudeAddUp += altitudeNumber;
powerAddUp += powerNumber;
speedAddUp += speedNumber;
}
MessageBox.Show("Alt add up:" + altitudeAddUp.ToString());
intervalAltitude = altitudeAddUp / difference;
intervalPower = powerAddUp / difference;
intervalSpeed = speedAddUp / difference;
intervalAverages.Add(new Tuple<int, int, int>(intervalAltitude, intervalPower, intervalSpeed));
MessageBox.Show("Interval: " + counter.ToString() + ": Avgs: " + intervalAverages[0]);
}
MessageBox.Show("Interval averages added. There were: " + counter + " intervals");
}
altitudeAddUp, powerAddUp and speedAddUp are always 0, but I can't figure out why it's not adding up. Probably a rookie error I just can't see it.
I've used a message box previously to test if altitudeNumber, powerNumber and speedNumber contain data and they do, but it won't add up.

I think the problem is that all your variables are integers. And integers don't have any decimal precision, that means that if an interval is 0.999, the actual integer value is 0 (0.999 doesn't exist as integer, to the value is truncated when you call ToInt32).
Use float, double or decimal, depending on the need of precision and range.

Related

Converting a ASCII value into its corresponding Integer value

The objective of this code is to add all the integers in a whole number into one value (e.g "2013" => 6),
In c# I have written the code so it outputs the number to its corresponding ASCII value one at a time, but I am at a loss at how to convert it back into its number value.
Note that I am new at C#
string Year;
int Total = 0;
int Adding = 0;
int Adding2 = 0;
Console.WriteLine("Write The year you want converted");
Year = Console.ReadLine();
for (int i = 0; i < Year.Length; i++)
{
Adding2 = Year[i];
Adding = Convert.ToInt32(Adding2);
Total = Adding + Total;
Console.WriteLine(Total);
}
You should sum values, not ascii codes:
...
for (int i = 0; i < Year.Length; i++)
{
Adding2 = Year[i];
Adding = Adding2 - '0';
Total = Adding + Total;
}
Console.WriteLine(Total);
In general case, you can use char.GetNumericValue():
// double: some characters have fractional values: '⅝'
double Total = 0.0;
foreach (char c in Year) {
double value = char.GetNumericValue(c);
// If character has value (e.g. 'A' doesn't have)
if (value != -1)
Total += value;
}
Console.WriteLine(Total);

Issues with looping code and do-while loops (c#)

static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
Hello. I am a beginner at coding, so I apologize if this is a poor attempt.
I am trying to make an app that records the amount donated by an individual, calculates a transaction fee, and outputs the results for each person. At the end, I am creating a final row of output that will state the total donations and the total transaction fees.
I am currently unsure how to properly implement the array into my loop, and am unsure if the loop is optimized in general.
Again, I am a beginner. I apologize for such code, but I'd love some clarification on these things.
Thank you!
First, your array declaration syntax is wrong. See this link.
So it should be int[] count = new int[donations+1];
Second, you need to declare and instantiate your amount and transfee variables outside of your loop.
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
This should be enough information to get you going again. Since you're learning, I don't think anyone would really unfold an answer for you that does the job you're trying to figure out :)
Your code :
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
You are actually increase i two times, then get values from count[i] assign to ct variable
See this sample :
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
It will cause IndexOutOfRangeException
Explain :
First Loop :
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
Second loop:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count[3] cause IndexOutOfRangeException
Something like count[i += 1] will make your code more difficult to maintain, in my opinion, you should avoid it if possible, try to write it explicity as you can

C#: finding the sum in a for loop

the question asks:
Write a program that reads from the screen two integer numbers min and max and outputs the sum of all squares of integers between min(including) and max(not including). If min is bigger than max, the program should output "min should be smaller than max!". Example:
>4
>9
190 (= 4² + 5² + 6² + 7² + 8²)
>14
>3
min should be smaller than max!
my code:
using System;
namespace ForLoops
{
class SumOfSquares
{
static void Main(string[] args)
{
int sum = 0;
int min = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
for (int i = min; i < max; i = i++)
{
sum = i * i;
}
Console.WriteLine(sum);
}
}
}
I keep getting 68 when i should get 190.
So the answer is you make it to For Loop statement so you can have the 2 examples. Answers at the same time.
int min = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
if(min > max)
{
Console.WriteLine("min should be smaller than max!");
}
else
{
int sum = 0;
for(int i = min; i < max; i++)
{
sum = sum + i*i;
}
Console.WriteLine(sum);
}
There are two flaws in your code:
The post-increment operator i++ increments i, but returns the previous value. So by i = i++ you never increase i because you always reassign the value as it was before the increment. This leads to an infinite loop.
You didn't sum up the products, but only assigned individual productes with sum = i * i;. You need to add them with sum += i*i;.
So your final loop could look like that:
int sum = 0;
for (int i = min; i < max; i++)
sum += i * i;
Linq is altertative to get rid of explicit loops (and let .net do the work for you):
using System.Linq;
...
int min = 4;
int max = 9;
int sum = Enumerable
.Range(min, max - min) // from min to max (not included)
.Sum(x => x * x); // sum up squares

Displaying Fibonacci sequence

wrote a program to calculate and display the first 20 fibonacci numbers, the sequence goes as follows:
1, 1, 2, 3, 5, 8, 13... (each number is the sum of the previous two numbers)
The problem is that the numbers that get displayed are from 2 onwards , the first and second numbers of the sequence do not get displayed , could someone tell me what needs to be done to correct this?
Code:
private void button1_Click(object sender, EventArgs e)
{
int previousNumber = 1;
int currentNumber = 1;
int nextNumber = 1;
while (currentNumber <= 11000)
{
nextNumber = previousNumber + currentNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
textBox1.AppendText(Convert.ToString(nextNumber) + " ");
nextNumber++;
}
}
I suggest carefully tracing through the logic and predicting what the computer will do at each step. Since the bug affects the very first output, you won't have to look at very many statements to encounter the problem. This is a basic skill for a programmer, so it will be well worth the time, especially since this sounds like homework.
Initially you need to display the current number twice before next number calculation. Also you need to move the number display before the next number calculation. Also next number should be previous number + currentNumber. I have made the changes to your code below which should work.
private void button1_Click(object sender, EventArgs e)
{
int previousNumber = 1;
int currentNumber = 1;
int nextNumber = 1;
textBox1.AppendText(Convert.ToString(currentNumber) + " ");
while (currentNumber <= 11000)
{
textBox1.AppendText(Convert.ToString(currentNumber) + " ");
nextNumber = previousNumber + currentNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
nextNumber = previousnNumber + currentNumber;
}
}
Since the first two digits in a Fibonacci are the seed values (1 and 1 or 0 and 1) you should print those first and then calculate the next values.
I would simplify the code. You can test it out at https://dotnetfiddle.net/3cV96L
int initialSeed = 1;
int currentNumber = 1;
//Write seed values
Console.Write("{0} {1} ", initialSeed, currentNumber);
while (currentNumber <= 11000)
{
currentNumber += currentNumber;
Console.Write(currentNumber + " ");
}
Just change int currentNumber = 0;

Push an Array forward so it will start from 150?

I have this function which is SMA (Simple Moving Average). The result in the array I display as graph in ZedGraph and now it will start from 0 to 1956. I want the graph to start from frameSize / 2 in this case example it will be 300 / 2 so 150 so the graph should start from 150 to 2016.
I don't want to make the graph to grow I mean the array should stay length as 1956 I just want it to be pushed by 150 indexes from the beginning so it will start from index 150 instead of 0.
So this is the SMA function:
private static double[] smaDoubles(int frameSize, int[] data)
{
int padding = frameSize / 2;
double sum = 0;
double[] avgPoints = new double[(padding + data.Length) - frameSize + 1];
for (int counter = padding; counter <= data.Length - frameSize; counter++)
{
int innerLoopCounter = 0;
int index = counter;
while (innerLoopCounter < frameSize)
{
sum = sum + data[index];
innerLoopCounter += 1;
index += 1;
}
avgPoints[counter] = sum / frameSize;
sum = 0;
}
return avgPoints;
}
In the for loop counter = padding before it was counter = 0 so the result of that is in the image here.
The green one is the SMA from this function. And the green start from 150 but ends at 1956 and it should end at 2106. When I moved it to start from 150 I want the whole graph to move as one unit by 150 so it will start from 150 and end in 2106. The red graph should stay the same all
How can I do it?
Now as it is in the image the graph end by 300 from the right edge.
This is the function as it is now i changed the line: double[] avgPoints = new double[data.Length - frameSize + 1]; this is how it was original so i changed it to this one now.
And the function get frameSize as 3 and data as [10] and im getting the same exception:
private static double[] smaDoubles(int frameSize, int[] data)
{
int padding = frameSize / 2;
double sum = 0;
double[] avgPoints = new double[data.Length - frameSize + 1];
for (int counter = padding; counter <= data.Length - padding; counter++)//for (int counter = padding; counter <= data.Length - frameSize; counter++)
{
int innerLoopCounter = 0;
int index = counter;
while (innerLoopCounter < frameSize)
{
// if (index < data.Length)
sum = sum + data[index];
innerLoopCounter += 1;
index += 1;
}
avgPoints[counter] = sum / frameSize;
sum = 0;
}
return avgPoints;
}
Not possible* Some languages, like pascal allow this, but not c#.
Why not just subtract the offset 150:
sum += data[index - 150];
*although not possible with an array, you can achieve the effect with a custom object that implements an indexed property.
private int[] _array;
public int this[int index]
{
get{ return _array[index - 150]; }
}
Are you sure:
for (int counter = padding; counter <= data.Length - frameSize; counter++)
shouldn't be:
for (int counter = padding; counter <= data.Length - padding; counter++)
And then your function that computes the moving average should go from counter - padding to counter + padding instead of from counter to counter + frameSize.
To debug this type of problem, it's often helpful to try it which a much smaller data set where you can compute the expected result by hand and see if your algorithm matches your expectations. I don't believe that your algorithm is necessarily calculating what you think it's calculating here. Try it with 10 data elements and a window size of 3 to see if you're getting the results that you expect.
Note, the first code line actually contains 2 logic errors, one of which is not necessarily apparent until you try the code 2nd line. The error is preserved for illustrative purposes

Categories

Resources