I can't get this simple calculation right - c#

I have a very small windows form application that calculates the storage cost for a warehouse depending on the amount of deliveries per year and presents the result in form of a chart.
It's doing what it's supposed to do, but there is just one little flaw.
There is 13 columns in the first bit and then there is 12 every other time.
I want it to always be 12.
I've been trying to reorder some lines of code, it looks like it's all ok, I'm probably just missing one line of code but can't figure it out
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StorageCost
{
public partial class Form1 : Form
{
public static int throughPot = 52000;
public static int weekly = 1000;
public static int weeklyPalletCost = 180;
public static int deliveries = 2;
public int storageCost;
public static int x = 0;
public static int currentPot = throughPot / deliveries;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
currentPot = throughPot / deliveries;
storageCost = 0;
x = 0;
chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
for (int i = 1; i < 51; i++)
{
currentPot -= weekly;
if (x>= 51 / deliveries)
{
x = 0;
currentPot = throughPot / deliveries;
}
chart1.Series[0].Points[i].YValues[0] = currentPot + 4000;
storageCost += currentPot * weeklyPalletCost;
x++;
}
cost.Text = "Total storage cost: £" + storageCost / 100;
chart1.ChartAreas[0].RecalculateAxesScale();
chart1.Update();
}
private void deliveriesUpDown_ValueChanged(object sender, EventArgs e)
{
deliveries = (int)deliveriesUpDown.Value;
Calculate();
}
}
}
this is the full code.
all I need basically is to get the same result in the beginning as from 13th column onwards
any help will be much appreciated.
thanks in advance.

It was because the first column was done outside of the for loop!
after commenting this out
//currentPot = throughPot / deliveries;
//storageCost = 0;
//x = 0;
//chart1.Series[0].Points[0].YValues[0] = currentPot + 4000;
and changing the loop to for (int i = 0; i < 51; i++)
I got it to work as expected.
Thanks #Grimm
I didn't know about this F11, F10 thing. This helped me a lot!

Related

Array of random numbers in C# / .NET framework

I am trying to create a lottery program that would generate random numbers between 1 - 35. These numbers need to be unique as well, they can not be the same. With C#, running on the .NET framework.
I have been trying to get it to work, but I keep getting errors and I don't understand why. I have been googling and looking at videos - still I don't get what I am doing wrong.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace help
{
public partial class Form1 : Form
{
// The array
TextBox[] TextBoxArray;
// the counter on how many times u pressed btn
private int counter = 1;
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
// The text boxes name 1 - 7
//TextBoxArray = new TextBox[] { Nr1, Nr2, Nr3, Nr4, Nr5, Nr6, Nr7 };
}
private void button1_Click(object sender, EventArgs e)
{
NrOfPull.Text = counter.ToString();
counter++;
// Keep getting an error
// Error CS0443 Syntax error; value
// they are talking about the Parse(TextBoxArray[].Text);
int number = int.Parse(TextBoxArray[].Text);
// Loop through
Random rand = new Random();
for (int i = 0; i < number; i++)
{
// Generate a alotter by turn
int storedNumber;
int[] randomLottoRow = new int[7];
for (int row = 0; row < 7; row++)
{
do
{
storedNumber = rand.Next(1, 35);
}
while (randomLottoRow.Contains(storedNumber));
randomLottoRow[row] = storedNumber;
}}
/*
* This will only let me generate numbers.. but wanna use Parse...
Random generator = new Random();
for (int x = 0; x < 7; x++)
{
TextBoxArray[x].Text = generator.Next(1, 35).ToString();
Console.WriteLine(TextBoxArray[x].Text = generator.Next(1, 35).ToString());
}
*/
}
}
}
Would love to get feedback on what I am doing wrong Thank you so much :)
This is one way of generating random sequences of numbers:
using System.Linq;
public static class Ex
{
static readonly Random rng = new Random();
/// <summary>
/// Randoms the sequence.
/// </summary>
/// <param name="maxValue">The maximum number in drawing.</param>
/// <param name="count">The number of numbers drawn.</param>
public static int[] Lottery(int maxValue, int count)
{
return Enumerable.Range(1, maxValue+1)
.OrderBy((x)=>rng.NextDouble())
.Take(count).ToArray();
}
}
static class Program
{
static void Main(string[] args)
{
var seq = Ex.Lottery(35, 8);
// draw 8 numbers ranging between 1-35
Console.WriteLine(string.Join(",", seq));
// 14,24,1,3,25,5,31,30
}
}
Here you go:
private TextBox[] TextBoxArray;
private Random rand = new Random();
public Form1()
{
InitializeComponent();
TextBoxArray = new TextBox[] { Nr1, Nr2, Nr3, Nr4, Nr5, Nr6, Nr7 };
}
private void button1_Click(object sender, EventArgs e)
{
int[] picks = Enumerable.Range(1, 35).OrderBy(x => rand.NextDouble()).Take(7).ToArray();
for(int i=0; i<picks.Count(); i++)
{
TextBoxArray[i].Text = picks[i].ToString();
}
}
This uses the same approach as John Alexiou for generating the random lottery pick numbers, but then also shows you how to put those numbers into your TextBoxes.

C# Random Number Generator Error

I am new to C# and random number generators, but need to code a simulator for a course I am taking. I am having difficulty with my for loop and my user-defined variables. I am coding in Visual Studio and need the user to select a number from a list (or input the number as text), but for the program to read it as an integer, not a string, and then use this integer as the number of times to generate a random number.
I will need to assign a probability distribution to this random number generator later, but right now I just need the thing to run! I am getting an error that it cannot covert int to string (or visa versa depending on how I code it). As well as getting an error that my local variable i is unassigned. I have looked at others codes for similar generators and I cannot see a difference in my for loop. Please help! Below is the form space C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GenerateProfile
{
public partial class Form1 : Form
{
int N;
public Form1()
{
InitializeComponent();
}
private void ChooseN_SelectedIndexChanged(object sender, EventArgs e)
{
N = ChooseN;
}
private void SBtn_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int num = rnd.Next(0, 100);
pi.Text = num.ToString();
for (int i; <= N; i++)
{
num = rnd.Next(0, 100);
pi.Text = pi.Text + num.ToString();
}
}
private void ClBtn_Click(object sender, EventArgs e)
{
Close();
}
}
}
I figured it out myself. I was not reading in ChooseN correctly. This fixed it.
private void Gen_Click(object sender, EventArgs e)
{
MessageBox.Show("N=", this.txtN.Text);
N = Convert.ToInt32(txtN.Text);
Random rnd = new Random();
int num = rnd.Next(-1, 1);
pitxt.Text = num.ToString();
int[] = { num };
for (int i = 1; i <= N; i++)
{
num = rnd.Next(-1, 1);
pitxt.Text = pitxt.Text + "," + num.ToString();
int[] = { int[], num };
}

Vector folding using Divide et Impera in c#

I'm in trouble on a College project.The project needs to be done using c# as a programming language and made in Windows Form like.
The program executes. I know it has flaws but at least i want to know how to get of this error: http://postimg.org/image/gwuzmyc73/ .
For the problem i need to fold a vector using the Divide et Impera.
I need to insert a number from the keyboard n, the generated vector would be like a=(1,2,3,4,5,6,7) and the final elements are 1,3,5,7.
The problem sounds like:
A vector of n elements.We define its folding by overlaping the 2 halfs,if n is odd.The 2 halfs are folded again until de subvector reaches 1 element.Utilize Divide et Impera.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plierea_Vectorilor
{
public partial class Form1 : Form
{
public int n;
public int i;
public int[] efinal = new int[50];
public string m = new string(new char[50]);
public int Ls, Ld;
public char[] aux = new char[50];
public Form1()
{
InitializeComponent();
}
public void Pliaza(int p,int q)
{
if (p == q)
{
efinal[p] = 1;
}
else
{
if ((q - p + 1) % 2 != 0)
{
Ls = (p + q) / 2 - 1;
}
else
{
Ls = (p + q) / 2;
}
Ld = (p + q) / 2 + 1;
}
Pliaza(p, Ls);
Pliaza(Ld, q);
/*
string ss = Ls.ToString();
string sd = Ld.ToString();
for (i = p; i <= Ls; i++)
{
aux[0] = 'S';
string.Concat(aux, ss);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
for ( i = Ld; i <= q; i++)
{
aux[0] = 'D';
string.Concat(aux,Ld);
string.Concat(aux, " ");
string m = aux.ToString();
string.Concat(aux, m[i]);
}
*/
}
private void button1_Click(object sender, EventArgs e)
{
Pliaza(1, n);
for (i = 1; i <= n; i++)
{
if (efinal[i]!=0)
{
label2.Text = Convert.ToString(i);
}
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
You're ALWAYS executing the Pliaza function FROM Pliaza. Aren't you missing a finish condition?
The recursive loop must be finished sometime in someway, else you will get that stack overflow.
A StackOverflowException usually means you have uncontrolled recursion going on. Reviewing your code, I see that Pliaza calls itself twice, using different variables ... but there is no path for Pliaza to exit without calling itself. You need some path to let the recursion bottom out. Very likely this would be to add a return; statement after the efinal[p] = 1; line.

sum of any four number always one in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
always one is the result of sum four numbers that less than one.
i changed the number to decimal and float
i used math,truncate
i wrote double before each number in calculation
still the result of sum is one
this my code and I added comment in the code in the place of my quistion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm3 : System.Web.UI.Page
{
public double[,] array = new double[4, 4];
public double b1vsb1c1=1.0;
public double b1vsb2c2;
public double b1vsb3c3;
public double b1vsb4c4;
// // .....here cotinue declear variable ,I deleteed to shoritng the code;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string isChecked2 = RadioButtonList1.SelectedItem.Value.ToString();
if (RadioButtonList1.SelectedItem.ToString() == "1")
{
b1vsb1c1 = 1.0;
b2vsb1c1 = 1.0;
}
else if (RadioButtonList1.SelectedItem.ToString() == "3")
{
b1vsb2c2 =3.0;
b2vsb1c1 =1.0/3.0;
}
// .....here cotinue test radio button value ,I deleteed to shoritng the code;
array[0,0]=b1vsb1c1;
array[0,1]=b1vsb2c2;
//....here cotinue assign value to array ,I deleteed to shoritng the code;
for (int i = 0; i < 4; i++)
{
sum = 0.0;
av = 0.0;
for (int j = 0; j < 4; j++)
{
sum=(double)sum + (double)array[i,j];
}
// here the sum always one why?!!
av = (double)sum/(double)4.0;
Response.Write(av + "| |");
// here is always result 0.25 why?
}
}
}
}
Try to use an Implicit typing : var to declare your varibales
I tried what you said; I have logic result : here is a sample exmaple:
public class Program
{
public static void Main(string[] args)
{
var p1 = 0.120336943441637;
var p5 = 0.01323706377858;
var p9 = 0.120336943441637;
var p13 = 0.120336943441637;
var sum = p1 + p5 + p9 + p13;
Console.WriteLine(sum);
}
}
Result = 0.374247894103491
Code Run

Why can't I find Sum() of this HashSet. says "Arithmetic operation resulted in an overflow."

I was trying to solve this problem projecteuler,problem125
this is my solution in python(just for understanding the logic)
lim = 10**8
total=0
found= set([])
for start in xrange(1,int(lim**0.5)):
s=start**2
for i in xrange(start+1,int(lim**0.5)):
s += i**2
if s>lim:
break
if str(s) == str(s)[::-1]:
found.add(s)
print sum(found)
the same code I wrote in C# is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static bool isPalindrome(string s)
{
string temp = "";
for (int i=s.Length-1;i>=0;i-=1){temp+=s[i];}
return (temp == s);
}
static void Main(string[] args)
{
int lim = Convert.ToInt32(Math.Pow(10,8));
var found = new HashSet<int>();
for (int start = 1; start < Math.Sqrt(lim); start += 1)
{
int s = start *start;
for (int i = start + 1; start < Math.Sqrt(lim); i += 1)
{
s += i * i;
if (s > lim) { break; }
if (isPalindrome(s.ToString()))
{ found.Add(s); }
}
}
Console.WriteLine(found.Sum());
}
}
}
the code debugs fine until it gives an exception at Console.WriteLine(found.Sum()); (line31). Why can't I find Sum() of the set found
The sum is: 2,906,969,179.
That is 759,485,532 greater than int.MaxValue;
Change int to long in var found = new HashSet<long>(); To handle the value.
You can also use uint however instead of long, however I would recommend using long.

Categories

Resources