javascript,calculator,keypress,keycode
if ((isShift == true && event.keyCode == 56) || event.keyCode == 106 || event.keyCode == 88) {calc.passMethod('multiply');} ...
Your program will work with those values, just use double precision, scanf has to use the %lf format specifier in that case. If you want much bigger values you will have to learn libgmp as mentioned in other answers.
You can check that your console (F12) is throwing error. Change document.getElementByID("a").value to document.getElementById("a").value JavaScript is Case-Sensitive. So that's why js does not find getElementByID...
java,loops,arraylist,switch-statement,calculator
I think a pretty standard algorithm to achieve this is Dijkstra's Shunting Yard Algorithm followed by postfix evaluation. You can read about it here, and the pseudocode is here, but you may need to have some understanding of basic data structures: http://en.wikipedia.org/wiki/Shunting-yard_algorithm . If you don't know about stack's, queue's...
This is a solution to my best interpretation to what you want. To me it seems like you want to take the displayed subtotal and calculate the taxes via javascript. This probably isn't the best way to go about it as I assume you'll be using those values later during...
Math.round(x) //x being your number you wish to 'round JSFiddle : http://jsfiddle.net/j37m78a4/2/ I have commented out the code that provided an answer with decimal point values. Uncomment that and comment out the line below it to see what the original answer was. :) If you don't know where to put...
python,calculator,division,subtraction
You can always use operandList[0] as the starting point if you wish, as long of course as operandList is not empty (up to you what you want to do when it is empty). if not operandList: raise ValueError('Empty operand list') # or whatever result = operandList[0] for operand in operandList[1:]...
java,swing,user-interface,calculator,jtextarea
You're adding your JTextArea, text, to your screen JPanel, screen.add(text, BorderLayout.NORTH); but you're adding screen to nothing, and so it makes complete sense that the JTextArea won't show. You should add the JTextArea to a container that somehow is either directly or indirectly added to your JFrame, else it's not...
Declare result once. double result = 0.0; if (CurChoice.equals("EUR")) { result = ExcAmount / Euro; //... } else { System.out.println(""); } double commission = (yn ? 0.01 : 0.02)*result; System.out.println( "commision: " + ... ); double netPayment = result - commission; yn is a terrible name, isAccountHolder might be better....
You are using three if/end if statements to process the button returned, you should only use a single if/end, and utilize else if in between. I have edited your code to fix it, and commented out the incorrect regions.
var res = new DataTable().Compute("1-2/3*4", null); edit: Also note you can use the fields in the data table to do functions like summing a column called "Total" var Total = DataTable().Compute("Sum(Total)", null); ...
As Klas Lindbäck has already pointed out, your code has problems when you parse constructs in parentheses. In principle, your algorithm should be something like this: If there are operators outside parentheses, find the one with the lowest precedence (that is a plus or minus rather than a times or...
For some reason you have 2 sets of variables with the same names. You have static variables inputA, inputB, inputC that are never assigned (so have the default value 0.0). You also have instance variables inputA, inputB, inputC. These are assigned, using the values you enter. Unfortunately whatever values you...
python,python-3.x,calculator,intervals
You are running the while loop until a and x becomes equal while you are actually looking for the intermediate value to be equal to x. You should write the loop like this instead: while float(CR5((a+x)/2.0))!= x: and while float(CR5((b+x)/2.0))!= x: result for x=4: (3.9999, 4.0001) ...
javascript,count,local-storage,calculator
I think you are searching for something like this: localStorage.setItem("setsgewonnen2.2", parseInt(gewonnen2.value) + 1); As normaly locall storage store everything as a string...
I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands. #include <stdio.h> #include <stdlib.h> #define ISIZE 100 // arbitrarily large int main(){ double num1, num2; int oper; char inp[ISIZE+1] = ""; printf("\tCalculadora\n\n"); printf("Introduza o...
I think the problem is that, when you determine the GCD, you are checking that the value is >= 1 in your for loop, even though it may be negative. In order to avoid this, you should capture the absolute values of the numerator and denominator when determining the GCD....
myDaysLeft = Double.parseDouble(amount.getText().toString()); should be myDaysLeft = Double.parseDouble(daysLeft.getText().toString()); However, you can just delete the 3rd and 4th lines as you are already setting the variables in the 1st and 2nd lines when you declare them. Why assign them twice?...
It is not due to overflow you get the strange result. Doubles can easily hold numbers in the range you are showing. Try to print the result without setprecision. EDIT: After trying long double x = 100.1; cout << x << endl; I see that it doesn't work on my...
I would probably just try parsing the values and then handle the exception. public class Adder { public static void main(String[] args) { //Array to hold the two inputted numbers float[] num = new float[2]; //Sum of the array [2] will be stored in answer float answer = 0; /*...
xcode,math,field,textfield,calculator
Have a look at NSExpression which lets you do things such as: NSExpression *expression = [NSExpression expressionWithFormat:@"4 + 5 - 2*3"]; id value = [expression expressionValueWithObject:nil context:nil]; // => 3 References NSExpression Class Reference NSExpression on NSHipster ...
It's because the input operator >> by default skips whitespace. Use std::noskipws input manipulator to change the behavior. Edit Addressing OP's comment about isspace() they could do: cin >> noskipws >> ch if (isspace(ch)) { // handle white space case } switch(ch) ... ...
java,calculator,roman-numerals
So for what it is worth, Roman Numerals could not represent Zero or negative numbers, but the following edits should let your program do it. Where you have: if (input <1 || input < 999) System.out.println("negative roman numeral value "); Use: if (input < 0){ s="-"; input *= -1; }...
After you fixed the duplicate code, you will need to fix a couple of other things. You need to add public class LilCalculator extends JFrame { on top In order for your GUI to show properly, you need to add the GroupLayout to your contentPane like this contentPane.setLayout(gl_contentPane); Then you...
The StackElement First, I think you meant to begin with a typedef your definition of the StackElement structure like: typedef struct StackElement { int data; struct StackElement *next; } StackElement; Then, the next pointer which is a member of the StackElement structure type points to a StackElement itself: The next...
java,switch-statement,case,calculator
Scanner sc = new Scanner(System.in); int nr = sc.nextInt(); for (int i = 0; i < nr; i++) { int prod = sc.nextInt(); int sum = 0; char ops; do { ops = sc.next().charAt(0); switch (ops) { case '*': prod *= sc.nextInt(); break; case '/': prod /= sc.nextInt(); break;...
If you call foileq(); instead of goto FOIL; the behaviour would be the same. In this case using goto does not make things more readable. There are very rare occasions where goto makes code better and this is not one of them. Also the continue you have currently written is...
javascript,jquery,html,calculator
You are better off using a single delegated event handler, connected to a parent element. This is more efficient than connecting loads of handlers: $(function () { $('.calculator').on("click", "button", function () { // Do something with the value of the clicked button... $(".draft").val($(".draft").val() + $(this).val()); }); }); JSFiddle: http://jsfiddle.net/TrueBlueAussie/cf8csjw1/ It...
you are adding the additional value even if the checkbox is not checked. you need to only add the additional value if the checkbox is checked. you can try this jsfiddle http://jsfiddle.net/16wws4w1/1/
python,bash,calculator,command-line-interface
You can use from math import * to import all constants and functions from the math module into your global scope....
java,user-interface,math,calculator
Looks like you have declared local variables to store your intermediate results, so these variables are reinitialized to 0 each time your action is performed. Instead, you might want them to be class properties, so the values in variables can "survive" several calls to actionPerformed method.
mpg = gets.to_s.chomp mpg == 23 Something is wrong here. You are asking it to give you a value, then having an evaluation which returns true/false just sitting there. I think you need to get rid of mpg = gets.chomp and turn mpg == 23 into mpg = 23....
ruby-on-rails,ruby,methods,calculator
The code is correct, but it doesn't make a lot of sense. You are passing the values to the initializer, therefore I expect your code to be used as it follows c = Calculator.new(7, 8) c.add # => 15 and it's probably the way you are calling it. However, this...
You forgot the parentheses to call the method: print CC.add().
Let that we have to make the following division: (a/b):(c/d) This is equal to (a/b)*(d/c) That being said the division can simply be done like below: static double CalculateDivisionResult(double a, double b, double c, double d) { return (a/b)*(d/c); } In the above: a is the num1Numerator. b is the...
Your question is missing some details, so here is a simple answer to begin with. (I guess your GUI is winforms, and you have a trigger for the calculate OnClick) To add text into your "Calculations" textbox the code you need is (for your example): private void calculateButton_Click(object sender, EventArgs...
function amountdue1() { if (document.calc.familyname1.value === null || document.calc.familyname1.value.length === 0) { alert("Please enter your family name"); } else { var numadults = document.calc.num_Adults1.selectedIndex; var numchildren = document.calc.num_Children1.selectedIndex; document.calc.totaldue.value = (numadults * adult) + (numchildren * child) + 10; }} You have added extra curly brace inthe function.Also,the function...
php,mysql,sql,calculator,poker
One way that is worth trying is to let the database do most of the work. Transfer your array to a temporary table with the primary keys of the matches to compare: create temporary table match_list (int pk1, int pk2); Now you can query the bigger table for the win/loss/draw...
c#,console-application,calculator
Change your operat function to private static string operat(string oper,double input1,double input2) And remove this line double input1 = 0, input2 = 0; And call operat function operat(opera,double.Parse(input1),double.Parse(input2)); ...
You have declared the constructor in Calculator.h but have not defined it in Calculator.cpp (or anywhere else). Adding Calculator::Calculator() { } to Calculator.cpp will fix the issue....
The comparison operation between the strings is not == but the equals() method: if(operator.equals("add")) ... else if (operator.equals("subtract")) ... else if (operator.equals("multiply")) ... else wrong input ...
java,methods,switch-statement,calculator
The biggest issue I can see is that your Operation() method is calling add(), subtract(), multiply() and divide() without parameters but you have defined those methods to take 2 digits each. I assume you are wanting to have getNumber() to work here but getNumber is currently just defining 2 digits...
javascript,html5,button,calculator
<input type="button" value="test" onClick="document.getElementById('textfield').innerHTML=this.value"> <div id="textfield"></div> ...
python,python-2.7,calculator,money
We need to run the balance count function for each new payment amount, since the interest sum will be smaller for bigger payments. So balance = 3329 annualInterestRate = 0.2 payment = 10 def year_balance(init_payment, init_balance): """ Calculates total debt after 12 months """ interest_sum = 0 unpaid = init_balance...
java,parsing,netbeans,calculator
You can do is when user press 2 , + , 2 and then if user again press +/- perform action for 2+2=4 and now pretend as 4+/-x ...
python,string,variables,integer,calculator
You are trying to assign to the result of an int() function call: int(sum1) = input('number') Everything on the left-hand side of the = sign should be a target to store the result produced by the right-hand side, and you are asking Python to store something in int(sum1). If you...
As mentioned in this answer using == for strings checks if they are the same item. In this case even though both CurChoice and one of the literal strings "EUR" may have the same value it will still be false as this is comparing references. So what's happening is they...
java,math,coordinates,calculator
private static final int startX = (Level.WIDTH / 2) - (Block.LENGTH * (Level.COLUMNS / 2)); This variable is evaluated once when the class it belongs to is initialized. At the time that happens, the variables it depends on (Level.WIDTH, Block.LENGTH, Level.COLUMNS) are probably still containing 0. When declaring a final...
java,android,android-studio,calculator
Create an Enum that represents Food, declare a constant for each food such as calories per 100 grams. Get a food string from your spinner, find the constant mentioned above and store it into a variable. Get the weight from your spinner/edittext, store it to a variable and convert...
java,switch-statement,calculator
import java.lang.System; import java.util.Scanner; public class Java{ public static void main(String args[]) { int result = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter number"); result = sc.nextInt(); System.out.println("Enter operation"); System.out.println("1.+"); System.out.println("2.-"); System.out.println("3.*"); System.out.println("4./"); System.out.println("5.="); int operation = sc.nextInt(); while (operation != 5) { System.out.println("Enter next number"); int number = sc.nextInt();...
Simply use log 2000 / log 1,024 instead.
java,eclipse,double,calculator
You need to use grade1.isEquals("A") to compare the strings. grade1 == "A" compares the object identity, which will be false since they are different objects. You might also consider doing away with the long 'if' chains and instead go with: answer += grade1.toLowerCase().indexOf("fdcba"); // returns the zero based index 0-4...
python,if-statement,while-loop,calculator,ignore
Here's your problem: choice = input("option: ") Under Python 3, this puts a string into choice. You need an integer: choice = int(input("option: ")) This will raise a ValueError if the user types something which is not an integer. You can catch that with a try/except ValueError block, or you...
You really should stop using goto statements and start using loops for this. (BTW I can see your label, but not your goto statement? ). To answer your second question, you could add a default statement in the switch statement, which will make it go back to the top if...
Your code doesn't run due to errors in it. alert(form.notwo.value + '/' form.none.value+ '=' + ans); for example misses a '+' and should be like this: alert(form.notwo.value + '/' + form.none.value+ '=' + ans); There are more like this but I'm sure you'll find them by yourself. Next try giving...
matlab,user-interface,math,plot,calculator
So in case the only thing you want to do is to store the data as long as the gui runs, there is an argument called handles, that is passed around. Most GUIDE callbacks have a syntax like function pushbutton1_Callback(hObject,eventdata,handles)` The struct handles can be used for this purpose. just...
function,swift,slider,calculator,updates
I'm a doofus. I just had to change miles to 500, instead of zero. Now it works. Sorry, guys.
Sidenote: This I tested before posting. There isn't anything wrong with your code. What I suspect is, your entire codes (HTML form and PHP) are inside the same page and that is why you are getting the "Undefined index" warning, as this is normal upon initial page load, because nothing...
To find the y-intercept (b), you need to set x to one of the x values and y to one if the y values and solve: y=mx+b b=y-mx The function could look like this: m=getSlope(x1,y1,x2,y2) b=y1-m*x1 return b The coordinates of the point would be (0,b), so you can return...
javascript,input,textfield,calculator
Basic Fixes There are many issues in your markup and code, starting with @Pointy's comment regarding your regexp. In the following, updated, working version, I have commented inline to explain these issues: function Calculate_Value(row) { // NOTE: Settle on the regexp approach to use – i.e. /.../ or // new...
Your to_i call is switched around here. print("What is the legnth of the base? ").to_i base = gets.chomp("base") Should be the other way 'round. print("What is the length of the base? ") base = gets.chomp("base").to_i Further, chomp will attempt to remove any occurrences of base or height from the string....
java,android,android-studio,sharedpreferences,calculator
In MainActivity take a static variable static int count=0; and get value String calorie = getIntent().getStringExtra("calorie"); and add it to count+=Integer.parseInt(calorie); and set the value to edittext textView1.setText(count+""); Hope this will helps you....
java,regex,string,optimization,calculator
First, you can create an Operation interface: public interface Operation { double apply(double x, double y); } Then, you create your concrete operations: public enum BasicOperation implements Operation { PLUS("+") { public double apply(double x, double y) { return x + y; } }, MINUS("-") { public double apply(double x,...
Try: let s1 = String(format: "%.19g", 1.2345) // 1.2345 Not sure if swift printf supports '%g' though. Edit: the 19 is based on the precision of a double, to display all (nonzero) digits, but not get ...0001 at the end. '%g' is the printf format specifier for 'natural' representation of...
algorithm,validation,parsing,input,calculator
One simple, standard algorithm for both checking the syntax of the input and optionally evaluating the expression is Dijkstra's shunting-yard algorithm, which was specifically designed to evaluate expressions like these. It can also be optionally modified to support syntax checking. Hope this helps!...
switch cases, in Java and nearly every other language that uses the switch construct, fall through to the one below them unless you use break. That is, if previousOperator is +, then not only does result+=number1; run, but then also result-=number1; and the other two statements after it. If previousOperator...
Hoo boy, there's a lot of things to cover. I'll try to get it all, but will start with working code. class Bill(object): # note: not Tip! def __init__(self, sub_total): self.sub_total = sub_total def calculate_tip(self, tip_pct): return self.sub_total * tip_pct def calculate_total(self, tip_pct): return self.sub_total * (1 + tip_pct) This...
the error message implies the missing ')' before the ';': for (var i = 0; i < indexAuf.length; i++;) { } correct is: for (var i = 0; i < indexAuf.length; i++) { } ...
haskell,recursion,binary,calculator
Something like binary2 :: Int -> [Int] binary2 x | x > 0 = binary x | otherwise = [] binary :: Int -> [Int] binary x | x `mod` 2 > 0 = binary2 (x `div` 2) ++ [1] | otherwise = binary2 (x `div` 2) ++ [0] So...
1/5 is meaningless when you deal with mod, since it only works with integers. When you write 5^-1 mod 18, it means the modular inverse of 5, in other words "the number by which you have to multiply 5 to get 1 mod 18". 5 * 11 = 55 =...
java,android,arraylist,spinner,calculator
do a list objects using a food class like { private string name; private int id; private double calories } and use that in your spinner...
I will not do the homework for you, but just a few tips: variable-names should start with a lowercase letter (TextField rezultat, not Rezultat) think about what exactly you expect to happen when you press the buttons: what should your calculator do, if you press 5 '-' '+' 55. should...
If you want to set the value of the clicked button to the answer field, you can simply use this: DEMO var a = document.querySelectorAll('input[type=button]'); for (var i = 0;i<a.length;i++) { a[i].addEventListener('click',addthis); } function addthis() { document.getElementById('input').value = this.value; } Please note that an input field has an value you...
The problem is in your interest rate used. You request the annual interest rate and never convert to a monthly interest rate. From https://en.wikipedia.org/wiki/Mortgage_calculator#Monthly_payment_formula: r - the monthly interest rate, expressed as a decimal, not a percentage. Since the quoted yearly percentage rate is not a compounded rate, the monthly...
It should be var profit = (sell_price - casecost) / packs; BUT - Never calculate currency with decimals in Javascript! Javascript will truncate decimal values when they become to long, possibly resulting in nasty rounding errors. Always multiply your values by 100, then calculate everything, and at last, divide by...
javascript,html,css,web,calculator
For problem 1, I believe this is a solution. I'm new to Javascript so pretty limited in how I can help. Here are the lines of code I changed: In HTML: <div class="row" id="requirements"> In CSS: #requirements { display:none; } In JS: document.getElementById("requirements").style.display="block"; ...
Do you really need your message box? If you follow Hans Passant's recommendations and start using TextBox, you could simply bind your variable properties and parse and format them. Have a look at the example below, it is more lines of code but gets you an opportunity to look at...
public function complete() { return $num1 * $num2; } There is no variable $num1 or $num2 created in this function. Of course it does not "read the variables' values". What you want probably is: public function complete() { return $this->num1 * $this->num2; } Have you read the chapter about classes...
javascript,html,onclick,calculator
I would suggest storing the price information as a numeric value somewhere, like in hidden input fields or data- attributes on the table cells, and create IDs on those elements that you can associate with the inputs for stock purchases. Then it's just a matter of doing some simple...
javascript,jquery,calculator,promotion-code
This should do it: var $total = $("#W_E-total"); // show total price /* PROMO CODE */ var max_price = parseInt($('#W_E-total').val()), finalprice = max_price; var promocode; $('#update').click(function () { promocode = $('#promocode').val(); if ((promocode == 'test') || (promocode == 'test1')) { finalprice = max_price * 0.9; } else if (promocode.length <...
You're using math_operator to store the selected math operator. Its value is only set when second_click == false (in btn_operator_Click()), therefore it seems clear why the second click doesn't change things.
As Jonesy (and others) mentioned in the comments, this would be a lot easier if you stored the current number as a string and appended characters to it, and then use Double.TryParse(..) to turn it into a number. However, if you're determined to treat it as a number, you can...
php,math,numbers,calculator,surface
It's simple. With this method, you can use any number and any size of materials. Store your materials into an array. Loop through on that array, make the calculations, and store the "rest" in another variable. If at the end there will be some rest, then add 1 more from...
java,swing,user-interface,calculator
Since you are a Java beginner, here are some tips that will make your life easier on the long run Initialize your buttons via a private function: Private void initializeButtons(){ //Initialize your buttons... } Call that function from your constructor. Do the same for setting the listeneres In your actionPerformed...
applescript,calculator,square-root
You can just set the exponent to 0.5. For example: set num_ to 25.1 set sqrt_ to num_ ^ 0.5 ...
Create a controller method. Then in the form_tag give the method's url. Then receive the parameters in that method. Then calculate and show the result. Suppose, Your current view calculator.html.erb show the form. in the form tag use <form action="<%= calculate_result_path %>" method="post"> Here, calculate_result is a method in any...
javascript,dynamic,calculator,record,keystroke
You can use local storage to save your calculations. Note that localStorage is just that, local. As in stored on the physical machine you are using. So if you were to visit this page on your laptop and do some calculations, then visit the page from your desktop, you would...
c,matrix,arduino,calculator,linear-algebra
It's a floating point error, the final value you are getting is very close to zero. Demo. Add a small epsilon value to your final test to allow for floating point inaccuracies: if(fabs(a[cant-1][cant-1]) < 0.000001){ lcd.print("No solucion"); /* if there is no solution print this*/ ...
java,exception-handling,calculator
You already have the code written out and all. Either start the "try" earlier, orsurround the first input with the same exact try catch: class MyGradeLevels { public static void main(String[] args) { System.out.println("Please enter your grade to begin!"); java.util.Scanner input=new java.util.Scanner(System.in); double grade; try { grade=input.nextInt(); if ( grade...
java,android,spinner,calculator
I'm doing this without a code editor so pardon the syntax errors but in general you should use an object to store the assoicated data. Use a custom adapter for your spinners. Here is some code to get you started. You should create an object called Food. public class Food...
ruby,algorithm,math,calculator
You need to compute the 1RM and then invert the formulas you link to using the new value if r (the number of repetitions your user wants to do). So with the formula you're using, and r_asked and w_asked the values for repetitions and weight : You now need to...
java,android,button,listener,calculator
Listener needs to be declared: private planOnClickListener myClickListener = new planOnClickListener(); And appropriate link to the listener: Button button4 = (Button)findViewById(R.id.button4); button4.setOnClickListener(myClickListener); ...