Ok so here's my problem. I have a vehicle constructor with several specs, and a class array that registers vehicles.
Within my form i wish to let the user search within that array for a specific value (in this case he shall input the type of vehicle and the year of the purchase, thus searching the array for them, and upon finding correspondents, he must then pick their price of acquisition and selling) and it shall return the sum of the profit.
Or in a simpler way: Profit = price of selling - price of acquisition.
The code I have thus far shows the profit individually and then the sum of the profits, how do I get just the latter?
int i;
bool found = false;
double lucro = 0;
for (i = 0; i < viaturas.NumElementos; i++)
if (viaturas.get(i).CVTipoVeículo == Int32.Parse(cbtipoveiculo.Text))
{
if (viaturas.get(i).CVDataVenda.Year == Int32.Parse(tbanopesquisa.Text))
{
double a = viaturas.get(i).CVPreçoVenda;
double b = viaturas.get(i).CVPreçoAquisição;
lucro += a - b;
found = true;
MessageBox.Show("O total de lucro das vendas em " + viaturas.get(i).CVDataVenda.Year + " foi de: " + lucro + "€", "Lucro", MessageBoxButtons.OK);
}
}
if (found == false)
{
MessageBox.Show("Conjunto de viaturas não existente!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
LimpaCampos();
}
If you want a value where you have all the profit summed then change your code to the following
int i;
bool found = false;
double lucro = 0;
for (i = 0; i < viaturas.NumElementos; i++)
if (viaturas.get(i).CVTipoVeículo == Int32.Parse(cbtipoveiculo.Text))
{
if (viaturas.get(i).CVDataVenda.Year == Int32.Parse(tbanopesquisa.Text))
{
double a = viaturas.get(i).CVPreçoVenda;
double b = viaturas.get(i).CVPreçoAquisição;
lucro += a - b; // Add it instead of overwriting
found = true;
//falta-me pô-lo a somar todos os lucros.
}
}
// Show a MessageBox here with a text (Sorry, I don't speak your language) that outputs your 'lucro' variable
If this is not what you meant, then I don't know how you can put all the profit into one value
Related
I am just trying to output the average of a case entry form. The case entry form is suppose to take only 7 inputs and convert it to a double and output the average of all the inputs but my average is not working. I am not too sure. Every time I try to use sum += userInput; and then move onto the if statement which calculates the average, it only outputs either all the numbers added together or some arbitrary number. I have tried just using the number 7 instead of the MaxDays constant which is 7. I am suppose to output the average to the user in a label. I have asked colleagues and look at reddit, youtube videos, other questions related to this issue but it does not really pertain to my issue.
Here is the code.
private void Enter_Click(object sender, EventArgs e)
{
bool isValid;
isValid = ValidateInfections();
double userInput;
if (double.TryParse(textBoxCaseEntry.Text, out userInput))
{
using TryParse.
if (userInput >= 0 && userInput <= int.MaxValue)
{
listBoxCases.Items.Add(textBoxCaseEntry.Text);
labelDay.Text = "Day " + (listBoxCases.Items.Count + 1);
for (int p = 0; p <= MaxDays; p++)
{
sum += userInput;
if (listBoxCases.Items.Count == MaxDays)
{
double dailyAverage = sum / MaxDays ;
labelAverageDailyCases.Text = "The daily case average is " + dailyAverage.ToString();
textBoxCaseEntry.Enabled = false;
Enter.Enabled = false;
}
}
}
}
else
{
MessageBox.Show("Calculations can not be performed as one or more validations have failed");
SetDefaults();
}
}
i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
Let me explain.
I am a high school student with not a lot of expirience programming in C#, we have an asigment to make a geometry calculator i got a triangular pyramid, but thats beside the point. The calculator is suposed to get an imput from the user and then with that given data calculate the surface and the volume.
double a = Convert.ToDouble(Console.ReadLine());
double h = Convert.ToDouble(Console.ReadLine());
double H = Convert.ToDouble(Console.ReadLine());
double area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
double volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Now thats easy for me , but a problem arises when the user does not know the value of one of the variables for example the hight.In such a instance the calculator is suposed to calculate it using the other two local variables.
double h = Convert.ToDouble(Console.ReadLine());
double h = Math.Sqrt(Math.Pow(a * Math.Sqrt(3) / 3, 2) + Math.Pow(H));
I know i know you cant do this but i coudn't find anything on the internet, so i beg you for help since this is 20% of my grade.
And if this can't be done do you have any other sugestions.
P.s. Sorry if my english is bad.
This is fairly simple to accomplish. Not having a variable means that you'll have a different formula/calculation depending on the missing variable, you can do this with if conditionals.
//Read them in as strings if you want to check if they're "_blank_", convert them
later.
string a = Console.ReadLine();
string h = Console.ReadLine();
string H = Console.ReadLine();
double area = 0;
double volume = 0;
if(a == "") //If it's blank, no entry do this code.
{
//This is how I'd convert it, just a little less pretty for the sake
//of understanding for you. You'd need to do this in every if block.
double returnedDoubleh = ConvertToDouble(h);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `a` is blank.
}
else if (h == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `h` is blank.
}
else if (H == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleh = ConvertToDouble(h);
//Have your formula if `H` is blank.
}
else //This is if none are blank OR More than one is blank which would crash if
more than one is blank..
{
area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
}
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Example Function to convert your string values.
public static double ConvertToDouble(string nonConverted)
{
double converted;
while (!double.TryParse(nonConverted, out converted) || String.IsNullOrWhiteSpace(nonConverted))
{
Console.Clear();
Console.WriteLine($"INVALID RESPONSE\n\r" +
$"\n\rTry Again");
nonConverted = Console.ReadLine();
}
return converted;
}
In your conditionals you can also use a "Variable" so instead of saying if(a == "") you could do something like if(a == "x")
I have made bisection method program in C# Console Application. Bisection method works, but for function which is already written in the code. I want to edit program that user can input function which they want to use for bisection method. For example Console.ReadLine() for input "x^2 + x - 2" and then I want it automatically written after return in the code below.
static double Function(double x)
{
return x*x - 2;
} //this is Function which I used in code.
Here is the whole code. (as i mentioned it works for function which is written in static double Function(double x) part
using System;
namespace MPI
{
class MainClass
{
public static void Main(string[] args)
{
// in [a,b]
double inPoc = 0; //a
double inKraj = 0; //b
double sredina = 0;
double tacnost = 0;
Start:
int i = 0; //brojac
Console.Write("Unesite početak intervala: ");
inPoc = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite kraj intervala: ");
inKraj = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite tacnost: ");
tacnost = Convert.ToDouble(Console.ReadLine());
sredina = (inPoc + inKraj) / 2;
if (Function(inPoc) * Function(inKraj) < 0)
{
while ((Math.Abs(inPoc - inKraj)) > tacnost)
{
sredina = (inPoc + inKraj) / 2;
Console.WriteLine("trenutno X: " + sredina);
Console.WriteLine("Funkcija za trenutno x ima vrednost: " + Function(sredina));
Console.WriteLine("");
i++;
if (Function(sredina) < 0)
{
inPoc = sredina;
}
else
{
inKraj = sredina;
}
}
Console.WriteLine("X: " + sredina);
Console.WriteLine("Broj izvrsenih koraka je " + i);
}
else
{
Console.WriteLine("Krajevi intervala funkcije su istog znaka");
Console.WriteLine();
}
goto Start; //sluzi da vrati program na pocetak kako bi ga opet koristili
}
static double Function(double x)
{
return x*x - 2; //primer funkcije
}
}
}
Looks like this question is asking about the same.
There are two solutions to do this:
Solution 1 - just use Flee.
Copy-paste from documentation:
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;
variables.Add("a", 100);
variables.Add("b", 1);
variables.Add("c", 24);
IGenericExpression<bool> e = context.CompileGeneric<bool>("(a = 100 OR b > 0) AND c <> 2");
bool result = e.Evaluate();
So you can do the same, just change input/output types and put your input line into the CompileGeneric
Solution 2 - parse input string manually.
So question can be divided to the two parts:
How to parse input string into the expression tree.
How to execute this tree.
For the first item - please check reverse polish notation. It allows to construct computation stack.
Next you will able to compute your expression tree. Each operand (after trimming) will have variable or integer constant. So just replace variable to the actual value and just parse string to the integer.
I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];