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,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) ...
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++) { } ...
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.
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...
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...
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...
Developing @jonrsharpe's comment, you should work with int variables holding pennies. The point here is that you have an integer amount of coins with float values, and you're mixing them when dividing, thus getting weird values. Also take into account that you should use the proper division operator. Here a...
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...
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...
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...
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...
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...
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...
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,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;...
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...
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...
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...
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,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();...
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...
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 <...
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...
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...
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 ...
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); ...
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*/ ...
javascript,html,alert,calculator
I'm not really sure what you are asking, please let me know if I misunderstood. There are much better ways to do what you want than to use alert boxes and prompts but if you must use them try this: function calculateTip (bill) { var rating, tip, answer; if (isNaN(bill))...
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...
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...
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...
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...
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.
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 =...
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...
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...
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...
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....
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...
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...
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 ...
This is a common basic mistake I see in beginners. You need to return your calculated value and store it. If not, you function is as good as "not doing anything". (Even though it did calculate, but you didn't store the calculated output). Your current function header is: void calculate(float...
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,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; }...
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....
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....
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 ...
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,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...
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...
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 ...
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"; ...
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....
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...
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,...
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...
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!...
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...
c++,qt,calculator,exponential,exp
void MainWindow::on_btnCalculate_clicked() { QString s; int intNum1 = ui->leNum1->text().toInt(); int intNum2 = ui->leNum2->text().toInt(); qreal result = qExp((qreal)intNum1* intNum2); s = QStrimg::number(result); ui->lblCalculate->setText(s); } ...
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...
You forgot the parentheses to call the method: print CC.add().
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...
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.
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,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...
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...
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; /*...
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...
jquery,function,drop-down-menu,calculator
Try this: JSFIDDLE $("select").on('change',function () { var total = 0; $('select').each(function () { var price = parseFloat($(this).find("option:selected").data("price")) || 0; total += price; }) if($('select:eq(0)').find("option:selected").index() == 3){ text = $('select:eq(0)').find("option:selected").text() ; $(".count h2").text(text); } else { $(".count h2").text('€ ' + total); } }) ...
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.
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...
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...
Essentially you are creating two values (one calculation for each field) then setting the inside of the display elements (the DIVs) to the values of the calculations: var someNumber = 10; var someNumberAfterCalculationOne = someNumber % 4; var someNumberAfterCalculationTwo = someNumber - someNumberAfterCalculationOne; document.getElementById("lt_input").innerHTML = someNumberAfterCalculationOne; document.getElementById("kg_input").innerHTML = someNumberAfterCalculationTwo; Here...
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); ...
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...
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...
android,eclipse,calculator,textwatcher
You can use TextWatcher et4.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { //...
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...
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...
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...
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....
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...
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,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...
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...
javascript,calculator,keypress,keycode
if ((isShift == true && event.keyCode == 56) || event.keyCode == 106 || event.keyCode == 88) {calc.passMethod('multiply');} ...
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.
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) ... ...