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
Related
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!
I am suppose to be writing a C# program in visual studios windows forms application that needs to implement the following functionalities:
Create 1,000 random numbers between 1 and 5000
Use the bubble sort algorithm and sort the 1000 numbers
This is the code that I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Prog7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
Random num = new Random();
string line = Environment.NewLine;
int nbr = num.Next(0, 5001);
textNumbers.Text = nbr.ToString();
for(int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
textNumbers.Text = textNumbers.Text + line + nbr.ToString();
}
}
private void SortBtn_Click(object sender, EventArgs e)
{
bool inorder = false;
while (!inorder)
{
inorder = true;
for (int i = 1; i <= 1000; i++)
{
if (swap(ref i, ref i + 1))
inorder = false;
}
}
for (int i = 1; i <= 1000; i++)
{
nbr = num.Next(0, 5001);
SortBox.Text = SortBox.Text + line + nbr.ToString();
}
}
private bool swap(ref int top, ref int bottom)
{
int temp;
if (top <= bottom)
return false;
temp = top;
top = bottom;
bottom = temp;
return true;
}
}
}
My original plan was to have the form have a button for generating the numbers and a button for sorting the numbers with two textboxes to list down the numbers.The code in my btnGenerate_Click works fine for generating the 1000 different numbers. But I am having a difficulty figuring out how I can input the bubble sort algorithm into this program. I looked up many examples online on what to do but many of the examples involve a array list which im not using. The program I have right now for SortBtn_Click obviously doesnt work. If anyone can give me suggestion on how to make it work or a easier way to create this program please let me know! I appreciate all the help anyone is willing to provide.
You can follow below steps to fix your issue:
Instead of creating new random number in SortBtn_Click function, use text present in textNumber textbox.
In SortBtn_Click function, First check textNumber is null or empty. If the string is null or empty, then throw an error.
In else part, split string and convert it into integer array.
you can split string using following code.
string[] strArr = textNumber.Text.split(Environment.NewLine);
Now convert string array into integer array.
int[] intArr = Array.ConvertAll(strArr, Int32.Parse);
Now apply bubble sort on intArr variable, store result in SortBox.Text text field
Note: As #JohnG mentioned about variables used in btnGenerate_Click (num, line, nbr) goes out of scope when execution leaves btnGenerate_click function. So you can not use those variables into other function. If you want to use those variables then declare that variables in class scope(Global declaration)
My goal is to make this program to take a number of pizzas and types of pizzas and count how much they cost. I decided to go with an object solution. The problem is it doesn't calculate it and it lets the program run even when The fields are empty. I literally have no idea why it doesn't calculate it. I'm also new to objects so there may be some logical mistakes.
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 Assignment_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void OrderButton_Click(object sender, EventArgs e)
{
double withTax = 0;
double tax = 0;
double subTotal = 0;
var pizzas = new Pizza[3];
if(ValidateAndDeclareQuantities())
{
pizzas = Declare();
subTotal = CalcSubTotal(pizzas);
tax = CalcTax(pizzas);
withTax = CalcWithTax(pizzas);
}
}
bool ValidateAndDeclareQuantities()
{
var combolist = new List<ComboBox>();
combolist.Add(comboBox1);
combolist.Add(comboBox2);
combolist.Add(comboBox3);
var textboxlist = new List<TextBox>();
textboxlist.Add(Quantity1);
textboxlist.Add(Quantity2);
textboxlist.Add(Quantity3);
for (int i = 0; i < 3; i++)
{
if (combolist[i].Text == "Cheese" || combolist[i].Text == "Vegetable" || combolist[i].Text == "Meat")
{ }
else combolist[i].Text = "Wrong input";
}
int[] Quantities = new int[3];
for (int i = 0; i < 3; i++)
{
if (int.TryParse(textboxlist[i].Text, out Quantities[i])&&textboxlist[i].Text!=null)
{ }
else { textboxlist[i].Text = "Wrong input"; }
}
return true;
}
Pizza[] Declare()
{
var pizzas = new Pizza[3];
string type;
int price;
type = comboBox1.Text;
price = int.Parse(Quantity1.Text);
Pizza pizza1 = new Pizza(type, price);
pizzas[0] = pizza1;
type = comboBox2.Text;
price = int.Parse(Quantity2.Text);
Pizza pizza2 = new Pizza(type, price);
pizzas[1] = pizza2;
type = comboBox3.Text;
price = int.Parse(Quantity3.Text);
Pizza pizza3 = new Pizza(type, price);
pizzas[2] = pizza3;
return pizzas;
}
double CalcSubTotal(Pizza[] pizzas)
{
double subTotal = 0;
for (int i = 0; i < 3; i++)
{
subTotal += pizzas[i].Price;
}
return subTotal;
}
double CalcTax(Pizza[] pizzas)
{
double tax = 0;
for (int i = 0; i < 3; i++)
{
tax += pizzas[i].Tax;
}
return tax;
}
double CalcWithTax(Pizza[] pizzas)
{
double withTax = 0;
for (int i = 0; i < 3; i++)
{
withTax += pizzas[i].WithTax;
}
return withTax;
}
void WriteOut(double subTotal, double tax, double withTax)
{
lblSubTotal.Text = "" + subTotal;
lblTax.Text = "" + tax;
lblTotal.Text = "" + withTax;
}
}
}
And the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_2
{
class Pizza
{
string type;
int quantity;
public double Price;
public double SubTotal;
public double Tax;
public double WithTax;
public Pizza(string type, int quantity)
{
this.type = type;
this.quantity = quantity;
FindPrice();
CalcSubTotal();
CalcTax();
CalcWithTax();
}
private void FindPrice()
{
switch (type)
{
case "Cheese":
Price = 9.95;
break;
case "Vegetables":
Price = 10.95;
break;
case "Meat":
Price = 11.95;
break;
}
}
private void CalcSubTotal()
{
SubTotal = Price * quantity;
}
private void CalcTax()
{
Tax = SubTotal * 0.13;
}
private void CalcWithTax()
{
WithTax = SubTotal + Tax;
}
}
}
Solution form
The quick answers:
ValidateAndDeclareQuantities never returns false. It should (probably) return false when you set "Wrong Input".
(Minor) int[] Quantities = new int[3]; is never used, aside from writing to it.
(Minor) var pizzas = new Pizza[3]; is also never used. It just gets overwritten by Declare a few lines later. Pizza[] pizzas=null; or just Pizza[] pizzas; is a better alternative. Not the greatest structure here though.
(Minor) Your variable called price in Declare is poorly named as it appears to actually be quantity. Things like this easily throw people off.
WriteOut is never called. withTax, tax and subTotal in OrderButton_Click are probably being computed correctly, but the values aren't being outputted.
The longer answer
It's a bit on the messy side! I appreciate that it's just a learning thing - we've all been there - but good code hygiene is just as important (if not more important) than the structure of the language.
UX: Don't overwrite what the user entered - specifically, don't replace the textbox input with "wrong input"; That's better off going on some other label. I would imagine you've already felt how weird this kind of experience is whilst testing the code.
Named things that don't need a specific class: Like a cheese pizza and a ham one. Enums are your friend! Use them instead of strings like "Cheese":
public enum PizzaType{
Cheese,
Tomato
}
Using enums in this way helps avoid the wonderful world of pain that is unexpected capitalisation and it's considerably faster too. CheEse pizza anyone?
Repetition: Large portions of your code are repetitive too; You'll want to practice avoiding it as much as you can. ('DRY'/ 'Don't Repeat Yourself'). A little forward planning helps massively. Everybody has preferences on code structure; mine here would be a separate "Pizza displayer" class which holds a quantity input box and does the validation too.
Junk: Slightly related to the above, you're creating a bunch of Lists and arrays which get created each time the function is called and then are just chucked out. Create a single array of some more abstract type (like an array of "Pizza displayers") and keep that array as a property on the Form. It's minor here, but being more aware of how much trash your program creates helps make your code go faster.
Notes on floats: You should never, ever use float/ double for money. Use decimal instead, or just do everything in pennies. Floating points aren't precise and you'll hit a rounding issue sooner or later.
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 };
}
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.