I have a textbox on my design form that have multiple numbers of double data type. I have a class that has a method to calculate smallest difference (positive or negative) between two consecutive numbers.
public decimal FindSmallestPriceChange()
{
}
On my form there is a label to display the result and a button event that calls the above method to calculate and display the smallest change between consecutive numbers in the text box.
private void btnSmallest_Click(object sender, EventArgs e)
{
lblSmallest.Text = aAnalyzer.FindSmallestPriceChange().ToString();
}
I have an array mentioned in the form class :
decimal[] prices = Array.ConvertAll(stringPrices, decimal.Parse);
I know I have to use for loop in my FindSmallest method but I don't know how to use the elements from the text box on design form in my separate class.
Can someone guide me on the right path on this.
The structure could be something like the following.
private void btnSmallest_Click(object sender, EventArgs e)
{
var stringPrices = new List<string>();
stringPrices.Add(comboBox1.Text);
stringPrices.Add(comboBox2.Text);
//TODO add error handling
decimal[] prices = Array.ConvertAll(stringPrices, decimal.Parse);
lblSmallest.Text = aAnalyzer.FindSmallestPriceChange(prices).ToString();
}
(...)
public static decimal FindSmallestPriceChange(IEnumerable<decimal> prices)
{
// There are many ways to do this. Here is one.
var sorted = prices.ToList();
sorted.Sort();
if( prices.Count() < 2 ) return 0;
decimal min = sorted[1] - sorted[0];
for(int i = 2; i < sorted.Count() - 1 ; i++ ) {
var diff = sorted[i-1] - sorted[i];
if( diff < min ) min = diff;
}
return min;
}
Test
Console.WriteLine(FindSmallestPriceChange(new []{66.6m}));
Console.WriteLine(FindSmallestPriceChange(new []{1m, 2m}));
Console.WriteLine(FindSmallestPriceChange(new []{1.1m, 4.4m, 2.2m}));
Console.WriteLine(FindSmallestPriceChange(new []{4.4m, -1.1m, 0m, 1.1m, 2.2m, }));
Output
0
1
1.1
-1.1
Related
prepare a form which accepts 2 numeric positive nos. On clicking generate button, a 2 dimension array of 10 x 10 size will completely filled up with random numbers between those 2 user inputted numbers.
You will print the entire matrix on screen in 10 rows by 10 cols using a function.
There will be one more button called transpose. When user clicks on this button, entire matrix will be transposed. i.e. the all the data elements in rows will be interchanged with columns. After transpose, it will get printed below again. Both print should be visible to users.
public void Button1_Click(object sender, EventArgs e)
{
int intLL = Convert.ToInt32(TextBox1.Text);
int intUL = Convert.ToInt32(TextBox2.Text);
int[,] arr = new int[size, size];
for (int row =0; row < size;row++)
{
for(int col=0;col<size;col++)
{
arr[row, col] = r.Next(intLL,intUL);
//Response.Output.Write(arr[row,col]+TextBox1.Text+TextBox2.Text+" ");
Response.Output.Write(arr[row, col] + " ");
}
Response.Write(" </br>");
}
}
public void Button2_Click(object sender, EventArgs e)
{
}
i get the answer how to generate matrix with random values but on button_2 click event how i get transpose of matrix to display it on same screen
Actually you are hardcoding the minimun and maximun values of your Random.Next call.
Just check what the user entered in the textboxes and use that values instead. After doing that you could do your traspoosing logic.
Something similar to:
int minValue = 0;
int maxValue = 0;
if (!Int.TryParse(tbMinimunValue, out minValue) || !Int.TryParse(tbMaximunValue, out maxValue))
{
Response.Write("Please enter numbers");
return;
}
// TODO: Add aditional checks like checking min < max, and min and max are positive values
Random r = new Random();
int size = 10;
int[,] arr = new int[size, size];
for (int i = 0; i < size;i++)
{
for(int j=0;j<size;j++)
{
arr[i, j] = r.Next(minValue, maxValue);
Response.Output.Write(arr[i,j]+" ");
}
Response.Write(" </br>");
}
i want to generate random number between (1 to 6),is there any way to change the chance of geting number 6 more than other numbers?
for example for this code
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
Let p be probability of any 1..5 numbers and 1 - p is a probability of 6:
//DONE: do not recreate Random
private static Random s_Generator = new Random();
private void pictureBox5_MouseClick(object sender, MouseEventArgs e) {
const double p = 0.1; // each 1..5 has 0.1 probability, 6 - 0.5
// we have ranges [0..p); [p..2p); [2p..3p); [3p..4p); [4p..5p); [5p..1)
// all numbers 1..5 are equal, but the last one (6)
int value = (int) (s_Generator.NexDouble() / p) + 1;
if (value > 6)
value = 6;
label2.Text = value.ToString();
}
That wouldn't be random then. If you wanted to weight it so you would get 6 half the time, you could do this:
m = u.Next(1,2);
if(m == 2)
{
label2.Text = "6";
}
else
{
label2.Text = u.Next(1,5).ToString();
}
Based on what weighting you want you could change it-> 3 instead of 2 get a 33.33% weighting and so on. Otherwise, as the commenter said, you'd have to look into probability distributions for a more mathematically elegant solution.
Depends on how more likely. An easy way (but not very flexible) would be the following:
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,7);
if (m > 6) m = 6;
label2.Text = m.ToString();
}
If you want a totally random distribution of 1...5 and just a skwed 6, then Dmitry's seems best.
If you what to skew ALL the numbers, then try this:
Create a 100 element array.
Fill it with the number 1-6 in proportions based on how often you want the number to come up. (make 33 of them 6, if you want 6 to come up 1/3rd of the time. Four 4s means it'll only come up one in 25 rolls etc. 15 or 16 of each number will make it about evenly distributed, so adjust the counts from there)
Then pick a number from 0...99 and use the value in the element of the array.
You could define the possibility in a percentage of getting each of the numbers in an array:
/*static if applicable*/
int[] p = { (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Ceiling((double)100/6) };
////The array of probabilities for 1 through p.Length
Random rnd = new Random();
////The random number generator
int nextPercentIndex = rnd.Next() % 100; //I can't remember if it's length or count for arrays off the top of my head
////Convert the random number into a number between 0 and 100
int TempPercent = 0;
////A temporary container for comparisons between the percents
int returnVal = 0;
////The final value
for(int i = 0; i!= p.Length; i++){
TempPercent += p[i];
////Add the new percent to the temporary percent counter
if(nextPercentIndex <= TempPercent){
returnVal = i + 1;
////And... Here is your value
break;
}
}
Hope this helps.
I've only been working with Arrays for a short while, and Im finding them much harder than working with Lists. For an assignment I have written a form with takes an input from a textbox and outputs a count,average, and total. The code is as follows:
int [] intScoreTotalArray = new int[20];
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
decimal decScoreCount = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
for(int i = 0; i < intScoreTotalArray.Length; i++)
{
decScoreTotal += intScoreTotalArray[i];
}
decScoreCount++;
decScoreAverage = decScoreTotal / decScoreCount;
But I also need to display it in a message box in a stong, and it only gives me the last value. My theory is that the problem lies in both boxes of code, or in the intial for loop.
private void btnDisplayScores_Click(object sender, EventArgs e)
{
decimal decScore = Convert.ToDecimal(txtScore.Text);
string strScoreTotal = " ";
for (int i = 0; i < intScoreTotalArray[i]; i++)
{
strScoreTotal += decScore.ToString() + "\n";
}
Array.Sort(intScoreTotalArray);
MessageBox.Show(strScoreTotal + "\n","Score Array");
Advice?
Why are you using an array to determine the count, average and total of a list of numbers? They aren't the best structure for a dynamic list of items as you have to declare an array's size when you initialize it. You SHOULD be using a list for this task.
As to why your code isn't behaving:
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
You are only assigning the first item in the array here.
It looks like you are using decScoreCount to keep track of the number of items in your array. I think you want to do this:
intScoreTotalArray[(int) decScoreCount] = Convert.ToInt32(txtScore.Text);
I am working on a employee paycheck calculator using several private methods. The methods will determine overtime hours and regular hours. I also must create methods for regular pay and overtime pay. My question is can I feed the results from the hours methods into the methods that will determine pay? If that is possible, how would it work? The method in question is CalculateBasePayAmount--can I pass a result from another method into here?
Here is a look at what I've got so far. Thanks for any help anyone could provide!
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Determine Hours Method
private decimal DetermineBasePayHours(decimal parhoursWorked)
{
decimal baseHours = 0;
decimal overtimeHours = 0;
if (parhoursWorked <= 40)
{
baseHours = parhoursWorked;
}
else if (parhoursWorked > 40)
{
overtimeHours = parhoursWorked - 40;
baseHours = parhoursWorked - overtimeHours ;
}
return baseHours;
}
private decimal DetermineOverTimeHours(decimal parHoursWorked, string parCategory)
{
decimal overtimeHours = 0;
if (parHoursWorked > 40 && parCategory!="MGR")
{
overtimeHours = parHoursWorked - 40;
}
return overtimeHours;
}
private decimal CalculateBasePayAmount(decimal basePayHours, string parCategory)
{
decimal basePay = 0;
decimal mgrWage = 20;
decimal salesWage = 15;
decimal staffWage = 10;
basePayHours= DetermineBasePayHours(basePayHours);
if(parCategory == "MGR" && basePayHours > 40)
{
basePay = 40 * mgrWage;
}
else
{
basePay = basePayHours * mgrWage;
}
if (parCategory =="SR")
{
basePay = basePayHours * salesWage;
}
else if (parCategory == "STF")
{
basePay = basePayHours * staffWage;
}
return basePay;
}
protected void butCalcPay_Click(object sender, EventArgs e)
{
////1. Declare Variables
//decimal mgrWage = 20;
//decimal salesWage = 15;
//decimal staffWage = 10;
//decimal basePay = 0M;
//decimal salesOvertime = 22.50M;
//decimal staffOvertime = 15;
//decimal overtimeHours = 0;
//decimal overtimePay = 0;
//decimal totalPay = 0;
decimal totalHours = 0;
decimal bpHours;
decimal otHours;
string empCat;
decimal basePay;
//2. Get Values for Variables
totalHours = Convert.ToDecimal(txtNumberHours.Text);
empCat = Convert.ToString(ddlCategory.SelectedValue);
// 3. Methods Called
bpHours = DetermineBasePayHours(totalHours);
otHours = DetermineOverTimeHours(totalHours, empCat);
basePay = CalculateBasePayAmount(totalHours, empCat);
// 4. Display Results
lblbasePay.Text = "Base Pay " + basePay.ToString("C");e here
can I feed the results from the hours methods into the methods that will determine pay?
In a manner of speaking, yes. Though I think the confusion is coming from the way you describe it and the terminology you use.
It's not entirely clear to me what specific values you're looking for in this case, but it looks like your methods essentially just accept some values, run some calculations, and return some values. Any code which call those functions will then get those returned values and can use them to call other functions. As a contrived example:
private int Method1(int someValue)
{
// perform some calculation, then...
return anotherValue;
}
private int Method2(int someValue)
{
// perform some calculation, then...
return anotherValue;
}
Then consuming code would be able to use those functions to perform larger calculations:
var calculatedValue = Method1(5);
var furtherCalculatedValue = Method2(calculatedValue);
This essentially "feeds the results" of the first function into the second function, in the sense that the result of the first function is then used as an input for the second function. The functions don't have any knowledge of each other, they don't "feed data to each other", in this case they simply return values based on calculations. Consuming code can choose to use the result of one function as a parameter to another function.
You do need to read more on programming and how/why we have methods that return values that the ones you mentioned above. Using your code above you'll want to use their values like this:
// basePayHours is the decimal amount returned by DetermineBasePayHours.
var basePayHours = DetermineBasePayHours(parhoursWorked);
// overTimeHours is the decimal amount returned by DetermineOverTimeHours.
var overTimeHours = DetermineOverTimeHours(parHoursWorked, parCategory);
// basePayAmount is the decimal amount returned by CalculateBasePayAmount.
var basePayAmount = CalculateBasePayAmount(basePayHours, parCategory);
delegate can also be used when a method is needed from another one .
Background:This is updated from 13 hours ago as I have been researching and experimenting with this for a few. I'm new to this programming arena so I'll be short, I'm teaching myself C# And I'm trying to learn how to have integers from a user's input into a textbox get calculated from a button1_Click to appear on the form. Yes, this is a class assignment but I think I have a good handle on some of this but not all of it; that's why I'm turning to you guys.
Problem:
I'm using Microsoft Visual Studio 2010 in C# language, Windows Forms Application and I need to create a GUI that allows a user to enter in 10 integer values that will be stored in an array called from a button_Click object. These values will display the highest and lowest values that the user inputted. The only thing is that the array must be declared above the Click() method.
This is what I have come up with so far:
namespace SmallAndLargeGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inputText_TextChanged(object sender, EventArgs e)
{
this.Text = inputText.Text;
}
public void submitButton_Click(object sender, EventArgs e)
{
int userValue;
if(int.TryParse(inputText.Text, out userValue))
{
}
else
{
MessageBox.Show("Please enter a valid integer into the text box.");
}
int x;
x = Convert.x.ToString();
int squaredResults = squared(x);
int cubedResults = cubed(x); squared(x);
squaredLabel.Text = x.ToString() + " squared is " + squaredResults.ToString();
cubedLabel.Text = x.ToString() + " cubed is " + cubedResults.ToString();
}
public static int squared(int x)
{
x = x * x;
return x;
}
public static int cubed(int x)
{
x = x * squared(x);
return x;
}
}
}
Now I can't run this program because line 38 shows an error message of: 'System.Convert' does not contain a definition for 'x' Also I still have to have an array that holds 10 integers from a textbox and is declared above the Click() method. Please guys, any help for me? This was due yesterday.
This looks like homework, so you should try a bit more than that. Here is what you could do: parse the string (say it's a comma-separated list of numbers), cast each value to int and populate your array. You can either call .Max() / .Min() methods or loop through the values of the array and get the max / min value. Here is a bit of code:
int n = 10;
int[] numbers = (from sn in System.Text.RegularExpressions.Regex.Split(inputText.Text, #"\s*,\s*") select int.Parse(sn)).ToArray();
int max = numbers.Max();
int min = numbers.Min();
//int max = numbers[0];
//int min = numbers[0];
//for(int i = 1; i < n; i++)
//{
// if(max < numbers[i])
// {
// max = numbers[i];
// }
// if(min > numbers[i])
// {
// min = numbers[i];
// }
//}
This in all probability being a homework I will not provide entire solution but just provide a hint.
Task to me seems to be to some how accept 10 integers and then show smallest and largest of them. For this there is no need to maintain an array (off-course only if maintaining an array is itself not part of the problem). You just need to keep track of current minimum and current maximum.
As and when you receive an input compare it with the current minimum and maximum and update them accordingly. e.g.
if(num < curr_min) curr_min = num;