Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So for some reason, it's adding the numbers fine, except for when i try to add with decimals... for example... if i type 2 + 2 it gives me 4, which is right, BUT if i type
2 + 1.2, instead of showing 3.2 on the textbox, it shows 14, so it's taking 1.2 as a 12... it's not counting the "." dot... the code is very long so I did a sample one with the same issue...
public partial class Form1 : Form
{
double num1, num2, answer;
string add, Op;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ("1");
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ("2");
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + (".");
}
private void button4_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = "";
Op = "add";
}
private void button3_Click(object sender, EventArgs e)
{
num2 = Convert.ToDouble(textBox1.Text);
switch (Op)
{
case "add":
answer = num1 + num2;
textBox1.Text = Convert.ToString(answer);
break;
}
}
}
so I created this;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var num1 = Convert.ToDouble("2");
var num2 = Convert.ToDouble("1.2");
var answer = num1 + num2;
Console.WriteLine(Convert.ToString(answer));
Console.ReadKey();
}
}
}
it does work.
now if you change
var num2 = Convert.ToDouble("1.2");
to
var num2 = Convert.ToDouble("1,2");
a comma, it will show the same result as you
can you check your localization setting and make sure "." (dot) is the decimal symbol/point for your computer? (control panel) or if you prefer run this and click on "additional setting..." button
C:\Windows\System32\rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,0
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 11 months ago.
i'm trying to create a calculator
After i rund the code... if i do a calculation like 9 x 9 i get result of 81
but when i try to use the result of 81 and divide by any number i get error System.ArgumentOutOfRangeException
9 x 9 = 81 then straigh / by any number i get error System.ArgumentOutOfRangeException
but
if i do type 81 and / by 9 i get correct answer of 9
the error comes after i do the first calculation...when i try to execute other calculation using the result i get that error
i tried to execute other calculation using the result of the first calculation
the code i try to execute is down below
namespace FormCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCopy_Click(object sender, EventArgs e)
{
Clipboard.SetText(textBox.Text);
}
private void buttonReset_Click(object sender, EventArgs e)
{
previousOperation = Operation.None;
textBox.Clear();
}
private void buttonClear_Click(object sender, EventArgs e)
{
if(textBox.Text.Length > 0)
{
double d;
if (!double.TryParse(textBox.Text[textBox.Text.Length - 1].ToString(), out d))
{
previousOperation = Operation.None;
}
textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1, 1);
}
}
private void buttonDiv_Click(object sender, EventArgs e)
{
if (previousOperation != Operation.None)
PerformCalculation(previousOperation);
previousOperation = Operation.Div;
textBox.Text += (sender as Button).Text;
}
private void buttonMult_Click(object sender, EventArgs e)
{
if (previousOperation != Operation.None)
PerformCalculation(previousOperation);
previousOperation = Operation.Mul;
textBox.Text += (sender as Button).Text;
}
private void buttonSub_Click(object sender, EventArgs e)
{
if (previousOperation != Operation.None)
PerformCalculation(previousOperation);
previousOperation = Operation.Sub;
textBox.Text += (sender as Button).Text;
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (previousOperation != Operation.None)
PerformCalculation(previousOperation);
previousOperation = Operation.Add;
textBox.Text += (sender as Button).Text;
}
private void PerformCalculation(Operation previousOperation)
{
List<double> listNumbers = new List<double>();
switch (previousOperation)
{
case Operation.Add:
listNumbers = textBox.Text.Split('+').Select(double.Parse).ToList();
textBox.Text = (listNumbers[0] + listNumbers[1]).ToString();
break;
case Operation.Sub:
listNumbers = textBox.Text.Split('-').Select(double.Parse).ToList();
textBox.Text = (listNumbers[0] - listNumbers[1]).ToString();
break;
case Operation.Mul:
listNumbers = textBox.Text.Split('*').Select(double.Parse).ToList();
textBox.Text = (listNumbers[0] * listNumbers[1]).ToString();
break;
case Operation.Div:
try
{
listNumbers = textBox.Text.Split('/').Select(double.Parse).ToList();
textBox.Text = (listNumbers[0] / listNumbers[1]).ToString();
break;
}
catch (DivideByZeroException)
{
textBox.Text = "kkkkkkkkk";
throw;
}
case Operation.None:
break;
default:
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox.Text += (sender as Button).Text;
}
enum Operation
{
Add,
Sub,
Mul,
Div,
None
}
static Operation previousOperation = Operation.None;
private void buttonResult_Click(object sender, EventArgs e)
{
if (previousOperation == Operation.None)
return;
else
PerformCalculation(previousOperation);
}
}
}
I cannot recreate your issue with your code, but there are a few things you can improve that might help you find your issue when you're done.
Firstly, you do not need to catch DivideByZeroException with floating-point arithmetic. It will return infinity and will never throw an exception.
Secondly, if you wish to inform the user of an invalid math operation as a result of using a divide-by-zero operation you can change that code:
case Operation.Div:
listNumbers = textBox.Text.Split('/').Select(double.Parse).ToList();
string answer = listNumbers[1] != 0 ?
(listNumbers[0] / listNumbers[1]).ToString() : "Divide by zero";
textBox.Text = answer;
break;
I wrote out a very simple code. I am trying to get it to do two things for me
I want it to continually show the user inputs and what the output would be. Right now it does not. I think this is a problem with my appendtext
should I use a try and catch for error handling? That's if the user enters more than one decimal my code crashes. I would like to know how to make it where it reverts back to one decimal and continues on.
Here is a snippet of my code.
Also to note, only in my addition method did I start the appendtext, since it didn't work and I kept getting stuck I stopped and came here...
private void button10_Click(object sender, EventArgs e) {
textBox1.AppendText(".");
}
private void button3_Click(object sender, EventArgs e) {
c = "+";
num1 = double.Parse(textBox1.Text);
textBox1.AppendText("+");
}
private void button12_Click(object sender, EventArgs e) {
c = "-";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button13_Click(object sender, EventArgs e) {
c = "*";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button14_Click(object sender, EventArgs e) {
c = "/";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e) {
num2 = double.Parse(textBox1.Text);
double result;
if (c == "+") {
result = num1 + num2;
textBox1.Text = result.ToString();
}
When you append "+", the num2 is equal to value1+"+"+value2 or something so try to use this code
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.Split('+')[1]);//bad idea but will work
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
also try
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.SubString(textBox1.Text.LastIndexOf('+')+1));
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
PS: try catch needed!
So far, my addition and subtraction work. But, my multiplication and division do not. This is because the first two numbers I put in get added and them the operation is done. Such as, if 9 * 9 + 3 should be 84, it is 21 on my calculator. That is because it is taking 9+9 + 3; as it only sees the last operator.
I have absolutely no idea how to fix this. Is there any helpful insight?
public partial class Form1 : Form
{
double num2;
double num1;
string c;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn0.Text;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn1.Text;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn2.Text;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn3.Text;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn4.Text;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn5.Text;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn6.Text;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn7.Text;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn8.Text;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn9.Text;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnAddition_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "+";
txtBox.Clear();
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "-";
txtBox.Clear();
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
private void btnDivision_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "/";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
double result;
num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
result = num1 + num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "-":
result = num1 - num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "*":
result = num1 * num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "/":
if (num2 != 0)
{
result = num1 / num2;
txtBox.Text = result.ToString();
}
else
{
txtBox.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
default:
result = 0;
break;
}
}
}
}
You need to do the previous operation before overwriting it with a new one:
private void btnAddition_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
num1 = calc(num1, num2, c);
c = "+";
txtBox.Clear();
}
where calc does the operation that you do on "=" now.
Two issues:
Look at your num1 variable every time after you click an operator other than equal. Say I start with 6*4-3. I press 6, then *. At this point num1 now becomes 6. Press 4 and - next. Now 4 is Added to Num1 making 10. Then 3 and equal is pressed, which probably gave you 7.
Second issue:
c is being overridden every time you press a different operator such as + or minus.
Solutions:
1) You could make an infix parser or
2) Modify your code to something as follow (giving example for subtraction)
private void btnSubtraction_Click(object sender, EventArgs e)
{
Equals()
c = "-";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
Equals();
txtBox.Text = Result.ToString();
result = 0;
}
private void Equals()
{
if (!double.TryParse(txtBox.Text, out num2)) return;
switch (c)
{
case "+":
result = result + num2;
break;
case "-":
result = result - num2;
break;
case "*":
result = result * num2;
break;
case "/":
result = result / num2;
break;
default:
result = num2;
break;
}
}
I think your problem is num1. Everytime you do an opperation you are just adding num1 with the value of the text box.
So I think when you press the buttons: 6*4-3= you should get 21, but you are acrually getting 7
This is because num1 is being added when you press * and - buttons, so you end up doing 6+4-3 = 7.
You need to change btnMultiplication_Click to something like:
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 * double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
and something similar for divide and subtract. I think subtract only works in your example because it's the last thing you do and the equals button handles it correctly.
I haven't tested this out but I think that's your problem
The mistake is that you're doing, for every operator:
num1 = num1 + double.Parse(txtBox.Text);
and that's wrong, because you're only adding every number you write in your calculator, except the last one, which is calculated correctly, due to btnEquals_Click.
In fact you check what operator you're using only when "=" is pressed, you have to do that for every operator you choose.
When any operation (+, -, /, *, =) is performed, the existing state (including the last operation) should be evaluated and replaces your first number, operation and second number.
Look at your criteria, here's the state before/after each action:
2+2+2= 6
2+
before: firstNumber=0 (default), operation="+" (default, hidden), secondNumber=2
after: firstNumber=2 (calc 0+2), operation="+", secondNumber=empty (awaiting input)
2+2+
before: firstNumber=2, operation="+", secondNumber=2
after: firstNumber=4(calc 2+2), operation="+", secondNumber=empty (awaiting input)
2+2+2=
before: 4 + 2
after: 6 + (empty)
2+3-1= 4
2+
before: 0(default) +(default) 2
after: 2 + (empty)
2+3-
before: 2 + 3
after: 5 - (empty)
2+3-1=
before: 5 - 1
after: 4 +(inferred) (empty)
6*4-3= 21
6*
before: 0(default) +(default) 6
after: 6 * (empty)
6*4-
before: 6 * 4
after: 24 - (empty)
6*4-3=
before: 24 - 3
after: 21 +(inferred) (empty)
Does that make more sense?
Also to follow standard calculator conventions you might want to consider allowing people to change the operation if the 2nd number is currently empty, e.g.
given this sequence:
6*4=-3= - perform 6*4 and see result ("="), then subtract 3 from that and show that result ("=")
6*
before: 0(default) +(default) 6 -> 6 * (empty)
6*4=: 6 * 4
after: 24 +(inferred) (empty)
6*4=-
before: 24 + (empty)
after special case: 24 - (empty)
6*4=-3=
before: 24 - 3
after: 21 +(inferred) (empty)
UPDATE:
To put this in terms of your code, you would need to change the +, -, /, * and = buttons to all work the same way. That is, take num1, c and the current value of double.Parse(txtBox.Text), perform that operation then update based on the new operation.
// is the current txtBox value new, so will be cleared and allow op change
private bool isNew = true;
// change this to default to +
string c = "+";
double num1 = 0;
private void Evaluate(string newOperand)
{
if (isNew)
{
// just update the operand, don't perform an evaluate
c = newOperand;
return;
}
double num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
num1 = num1 + num2;
break;
// etc for -, /, *
// for "="
default:
num1 = num1 + num2;
break;
}
isNew = true;
c = newOperand;
}
// this can be assigned as the handler for buttons 0 - 9
public void btnNumber_Click(object sender, EventArgs e)
{
var button = sender as Button;
txtBox.Text += button.Text;
isNew = false;
}
// this can be assigned as the event handler for all operations: +, -, /, *, =
public void btnOperation_Click(object sender, EventArgs e)
{
var button = sender as Button;
Evaluate(button.Text);
}
I have changed the whole purpose of num1 from the way you did it, so it is now the firstNumber as in my examples above.
You might want to add a clear all that will reset num1 to 0 and c to +. You could also do this in your existing btnClear_Click by detecting a 2nd press, like many calculators do:
public void btnClear_Click(object sender, EventArgs e)
{
if (isNew)
{
num1 = 0;
c = "";
// text box should already be empty
}
else
{
isNew = true;
txtBox.Clear();
}
}
Hello I just write a simple calculator in C# and I want to improve my program to handle parentheses.
Here is my button to add 1(digit):
private void btnOne_Click(object sender, EventArgs e)
{
txtResult.Text += '1';
}
This is a method for my Plus button:
private void btnPlus_Click(object sender, EventArgs e)
{
lblChar.Text = "+";
num1 = float.Parse(txtResult.Text);
txtResult.Text = "";
}
And this is for to calculate final result:
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = float.Parse(txtResult.Text);
if (lblChar.Text == "+")
{
num3 = num1 + num2;
txtResult.Text = Convert.ToString(num3);
}
}
Anyone can help me to write parentheses for my program?
You can use NCalc - Mathematical Expressions Evaluator for .NET
Expression e = new Expression("2 + (3 + 5)*6");
var result = e.Evaluate();
I am new to c# , i have read few basic concepts and now want to learn actual programming , thats why i started out with simple Calculator program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void one_Click(object sender, EventArgs e)
{
textBox1.Text =textBox1.Text+one.Text;
}
private void clear_Click(object sender, EventArgs e)
{
textBox1.Clear();
// textBox1.Text = " ";
}
private void two_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+two.Text;
}
private void three_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+three.Text;
}
private void four_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+four.Text;
}
private void five_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + five.Text;
}
private void six_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + six.Text;
}
private void seven_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + seven.Text;
}
private void eight_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + eight.Text;
}
private void nine_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + nine.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(textBox1.Text) ;
textBox1.Clear();
}
private void ten_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ten.Text;
}
private void equal_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(textBox1.Text) ;
textBox1.Text = num2.ToString();
num1 = 0;
}
}
}
This code is given in the book and they said its working .Actual problem is it works ONLY some times and some times it gives error as " Input string was not in a correct format "
What is the solution .
My second question is -- is this right approach to learn any programming language ? or should i just continue reading some more stuff n programs ?
If some one can help me with websites containing sample programs it will be very helpful .
Your problem is parsing the double. The Parse function cannot parse a string that does not represent a double.
Consider the string "135.42", this could easily be parsed to the double value 135.42. But what if the string was "Abc#%%#". This does not represent a double value and that is where you are getting your exception.
If this is your first programming language, you should read a introductory book to C# as a new programmer.
If double.Parse can't parse the string into a double then an exception is thrown. However, it's often better to use double.TryParse as it will simply return false instead of throwing an exception.
double tmp;
if(double.TryParse(textBox1.Text, out tmp))
{
num2 = num1 + tmp;
textBox1.Text = num2.ToString();
num1 = 0;
}
else
{
//double could not be parsed from textbox
}
You need to restrict the user to input only numbers in your textbox. You can do it by using keydown event of textbox. Where you will check if inputed char was numeric, only then keep it in the textbox. Here is the solution of your problem. Have a look at this:
How do I make a textbox that only accepts numbers?
For learning C#, i would prefer:
C# 5.0 in a Nutshell: The Definitive Reference
Before you do double.Parse() you should verify the user input, i.e. That it is an actual number.
I would suggest using TryParse method instead, as such:
double num;
bool isNum = double.TryParse(Str, out num);
if (isNum)
{
//Calculate here
}
If you wanted to handle invalid arguments more gracefully you could use Double.TryParse instead.
Here is the magic: double.Parse(textBox1.Text)
This function accepts only numbers (with comma or dot depends on your culture) in the string. If you pass anything else you will receive the given exception. Validate the input before you parse it or Use TryParse
double valueinDouble;
var success = double.TryParse(textBox1.Text), out valueinDouble)
if (success)
{
// do the calculation here
}
The TryParse has another implementation where you can specify the culture.
var success = double.TryParse(textBox1.Text), NumberStyles.Any, new CultureInfo("en-US"), out valueinDouble)