JavaScript - Help With Math Functions..looping Them
Im trying to get all of these math functions into one table with each one going into an individual row. The following is what my Grad Assistant gave us as instructions..he is not real helpful..lol The goal of project to is to create a webpage that makes use of javascript to perform a dynamic number of operations. The program must first ask for a number of operations to perform (n).It is therefore required that a loop construct be used. The program will then ask the user n times what operation they would like to perform and the appropriate inputs for that operation. All of the operations will use integer type inputs except ceiling, floor, and round which will use float types. The required operations for this project will be 1. + 2. * 3. / 4. % 5. min 6. max 7. floor 8. ceil 9. round The output of each operation will be stored in a table. The required outputs for each row are the operation requested, the expression for the operation showing its structure (see below), the result of the operation and additionally a random number. The random number should be within one and the number of operations requested. (ex: 5 operations requested, random number is in the range 0-5) A sample of what this output will look like is shown here. let me know if you can help it is much appreciated..the course book does not cover most of what is being taught and in class time could be better spent self taught! lol ..midterms suck and its almost time for the weekend so I could really use some help!! thx again Similar TutorialsHi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. I can't wrap my head around this at the moment so with the hope of finding someone willing to take a stab I am posting this to all of you. I need to create a savings ticker that shows $ saved per second. The data is as follows then = date script is created now = current date std = savings to date in $ avg = average savings per second in $ It would need to calculate the difference in time between then and now, convert that to an integer that can then be multiplied by avg then std would be added. thanks in advance I'm new to programming and can't figure out why this won't work: Code: print " var 1A == Math.sqrt(Math.pow(B,2) - Math.pow(C,2)); \n"; print " var 1B == Math.sqrt(Math.pow(A,2) + Math.pow((F + G),2)); \n"; print " var 1C == B + D; \n"; print " var 1D == C - B; \n"; print " var 1E == E; \n"; print " var 1F == (Math.sqrt(Math.pow(C,2) - Math.pow(A,2)) - G); \n"; print " var 1G == (Math.sqrt(Math.pow(C,2) + Math.pow(A,2)) - F); \n"; print " var 1H == ((F + G) / B); \n"; I have tried debugging it using Firebug and I get this error: Quote: identifier starts immediately after numeric literal I get the error on the line with var 1A, but I'm pretty sure that 1B, 1F, and 1G would all have the same error. Thanks for the help in advance guys! BTW the reason why the code is being printed is because I'm programming with Perl and running on a webpage using html and javascript. hey. im working on a facebook app.. this is what i got so far. PHP Code: <script language="JavaScript"> <!-- var theImages = new Array() theImages[0] = "http://img688.imageshack.us/img688/4787/logo1tq.jpg" theImages[1] = "http://img641.imageshack.us/img641/8292/logo2yex.jpg" theImages[2] = "http://img864.imageshack.us/img864/4097/logo3ik.jpg" theImages[3] = "http://img543.imageshack.us/img543/9046/logo4pu.jpg" theImages[4] = "http://img21.imageshack.us/img21/2567/logo5q.jpg" theImages[5] = "http://img842.imageshack.us/img842/696/logo6o.jpg" theImages[6] = "http://img85.imageshack.us/img85/7831/logo7k.jpg" var j = 0 var p = theImages.length; var preBuffer = new Array() for (i = 0; i < p; i++){ preBuffer[i] = new Image() preBuffer[i].src = theImages[i] } var whichImage = Math.round(Math.random()*(p-1)); function showImage(){ document.write('<img src="'+theImages[whichImage]+'">'); } //--> </script> <script language="JavaScript"> <!-- showImage(); //--> </script> now i want that the app posts the random image automaticlly to the useres timeline.. for example: if the random image is theImages [3] then it should post the image theimage [3] to the users timeline.. i see alot of facebook apps doing this.. thanks in advance How can you add/substract two numbers in javascript if they are written out as words such as one|two|three|four|five|six|seven|eight|nine|ten. Code: if ((word[0].match(/one|two|three|4|five|six|seven|eight|nine|ten/)) && (word[1].match(/plus|add/)) && (word[2].match(/one|two|three|4|five|six|seven|eight|nine|ten/))) { document.result.result.value = "The answer is ?"; return true;} I'm making a 3d pie chart. I have the points and the correct method to fill everything but when the slice rotates I want to make the outer edge filled, but in order to do that I have to figure out what math I use to find the leading edge. I made a picture to hopefully explin what I need to find. I figure it might be the tangent but I was hoping someone smarter than I could send me in the right direction. I just need someone to help me pinpoint my next step. Right now the rendering uses start and end angles to first make the top and bottom sections, fills them and then it makes an arc along the top of the slice from start to end then from end to start on the bottom slice and completes the polygon by going back the first point in the arc. I need to make two separate polygons if the end or start are further from the center than the( tangent?) point. Need some advice. Hope someone has an idea. I'm a student learning javascript, I'm having a very basic problem. I have to write a script that outputs XHTML text that keeps displaying in the browser window that multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. This is the code i have, Code: <!-- var product=2; while { product =2*product; } document.writeln( +product+ ); // --> And it pretty much does nothing. Help would be much appreciated Dave Just started to learn java & came up with the following, but can't get the math.round to work. Anyone able to tell me where I'm going wrong please ??? <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) } function roundme(len, wid, sq){ math.round.len; wid = math.round(wid); sq = math.round(sq); alert(len); }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) }; function changeme(id, action) { var val = document.getElementById("sizegroup"); if (val.style.display == 'none') { val.style.display = 'block' } else { val.style.display = 'none' } }; function convert(num, dec){ var val = document.getElementById("boxa").value; var val2 = document.getElementById("boxb").value; if(isNaN(val)){return val}; if(isNaN(val2)){return val2}; document.getElementById("boxc").value = val * metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; document.getElementById("boxd").value = val2 * metrics[document.getElementById("choice2").value]/ metrics[document.getElementById("choice4").value]; document.getElementById("sqmtrs").value = document.getElementById("boxc").value * document.getElementById("boxd").value ; document.getElementById("boxc").value = math.round(document.getElementById("boxc").value); }; var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <p>Length in imperial-metric / Width in imperial-metric</p> <div><input id="boxa" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice1" onchange="convert();"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxb" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice2" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></div> <div><input id="boxc" style="width: 40px;" type="text" disabled="disabled" /><select id="choice3" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxd" style="width: 40px;" type="text" disabled="disabled" /><select id="choice4" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></div> <p> </p> <div>Total sq metres : <input id="sqmtrs" style="width: 40px;" type="text" value="" disabled="disabled" /></div> <p> </p> <div class="label">Please round up to half a metre when choosing</div> <table border="0" cellspacing="0" cellpadding="5"> <tbody> <tr> <td>Round:</td> <td><input type="text" name="numberfield" value="" /> to <input type="text" name="decimalfield" value="2" size="3" /> decimal places</td> </tr> <tr> <td>Result:</td> <td><input type="text" name="roundedfield" value="" /> <input onclick="roundNumber(numberfield.value, decimalfield.value);" type="button" value="Calculate" /></td> </tr> </tbody> </table> Either I made an uh-oh, or there is a serious problem with Javscripts math functions. Math.sin(x) returns the sine of x in radians. Last time I checked, the sine of pi radians is 0, but in javascript: Code: Math.sin(Math.PI) // returns 1.2246467991473532e-16 Any idea why? Julian ok so heres where I stand, I don't know too much about javascript. Just enough to get me by. I am a PHP developer, I know how to do this in PHP but the client insists on doing it through javascript. Basically there are 3 different form values that determine the Premium Death Benefit Ratio. This is the formula the client wants: Premium to Death Benefit Ratio % (Created by formula = Annual (Level) Premium Amount (Divided by) Death Benefit Amount (equals a percentage) That percentage multiplied by Life Expectancy The 3 form values in the formula would be Annual Premium Amount (fypremium), Death Benefit Amount (dbp), Life Expectancy (average_le) I was messing around with javascript trying to figure it out and I have gotten no where since I am not used to writing formulas in JS. Anyways here is what I have so far: Code: function calculateLE(inputFieldId1, inputFieldId2, inputFieldId3, outputFieldId){ var DBR; var input = document.getElementById(inputFieldId).value; APA = document.getElementById(fypremium).value; DBA = document.getElementById(dbp).value; LE = document.getElementById(average_le).value; formula = document.getElementById(fypremium).value / document.getElementById(dbp).value = formula3; formula2 = document.getElementById(average_le).value * formula3; if { APA = "" } { document.getElementById(outputFieldId).value = "Error getting Annual Premium Amount"; } else if { DBA = "" } { document.getElementById(outputFieldId).value = "Error getting Death Benefit Amount"; } else if { LE = "" } { document.getElementById(outputFieldId).value = "Error getting Life Expectancy"; } else { document.getElementById(outputFieldId).value = formula3; } } Now I honestly have no clue if I am on the right track but what i've found on the net hasnt really pointed me in the right direction Here is the form values. Code: <input type="text" name="fypremium" id="fypremium" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> <input type="text" name="dbp" id="dbp" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> <input type="text" name="average_le" id="average_le" onblur="calculateLE('fypremium', 'dbp', 'average_le', 'premium_dbr')"> In a nut shell the values for the 3 inputs stated above will determine premium_dbr's value. fypremium / dbp = percentage; average_le * percentage = DBR (death benefit ratio); If someone could point me in the right direction to finishing this id be very greatful. I am at a lost, new to JavaScript and not sure why I am getting Nan Code: <script type="text/javascript"> var num1; var num2; var num3; var ave_num=Math.round((num1 + num2 + num3) / 3); //follow prompts to enter numbers and print average </script> Hi. I'm in JS kindergarten. I have a form with a field that asks for a full year. If the year is greater than 20 years ago, I'd like additional form fields to be revealed. If the year is equal to or less than 20 years ago, it will not reveal the fields. (And it should be based on getFullYear(), so I don't have to update the script every year, yeah?) I figured out how to script onclick functions and some basic .value == functions in order to show/hide just about every type of form field. So I don't need that info. But I'm unsure of how to calculate the value. I'd be interested to see your solutions. No rush. Thanks in advance. Code: <script type="text/javascript"> function countItDown(){ var current=parseFloat(document.getElementById("currentsecondscount").value); var seconds=current; document.getElementById("debug").innerHTML="S "+current; var minutes=Math.floor(seconds/60); document.getElementById("debug").innerHTML+="<br>M "+minutes; var hours=Math.floor(minutes/60); document.getElementById("debug").innerHTML+="<br>H "+hours; var days=Math.floor(hours/24); document.getElementById("debug").innerHTML+="<br>D "+days; var remainingseconds=seconds-(minutes*60); document.getElementById("debug").innerHTML+="<br>RS "+remainingseconds; var remainingminutes=minutes-(hours*60); document.getElementById("debug").innerHTML+="<br>RM "+remainingminutes; var remaininghours=hours-(days*24); document.getElementById("debug").innerHTML+="<br>RH "+remaininghours; if(days<10){ days="0"+days; } if(remaininghours<10){ remaininghours="0"+remaininghours;} if(remainingminutes<10){ remainingminutes="0"+remainingminutes;} if(remainingseconds<10){ remainingseconds="0"+remainingseconds;} document.getElementById("days").innerHTML=days; document.getElementById("hours").innerHTML=remaininghours; document.getElementById("minutes").innerHTML=remainingminutes; document.getElementById("seconds").innerHTML=remainingseconds; document.getElementById("currentsecondscount").value=(current-1); } </script> ....... <input type="hidden" id="currentsecondscount" value="<?=$seconds;?>" /> ....... Chrome/IE/etc on Left... FF 3.6.3 [windows] on Right im not sure why Firefox is doing this. it seems to work fine on Firefox 3.6.3 for Mac... Hi. I am new to javascript programming so please go easy on me. I am creating a site for a flooring store and need to include a price calculator/estimator. What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and th tird being selected from the pulldown. Can someone please educate me on how to do this? i had to create a function to calculate percentage and round to integer need 2 parameters of item and sum function will return value of item variable divide the sum by 100 and round to nearest integer using Math.round this is my code that i came up with Code: function calcPercent(item,sum){ // script element to calculate the percentage which is rounded to the nearest integer var items = Math.round( (item/sum)*100); // script element to get the percentage return items; } calcPercent(1, 3); Does this make sense? thanks Hi. I am new to javascript programming so please go easy on me. I am creating a website for a flooring store and need to include a price calculator/estimator. What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and the third being selected from the pulldown. Can this be done with Javascript, and can someone please educate me on how to do this? I have this simple manual photo slide show. It shows four photos and when you click the next button and it moves one photo over and one photo back for the previous button. I have to moving by changing the CSS property of 'left' by 195 pixels each move. So for it to move next it will subtract 195 pixels from the left property and for moving back it add 195 pixels to the left property. I have the code setup so when you click it changes the property of left to either -195 or 195 pixels but I need it so it actually does the math, not just give it a set value. But I don't know how to do that. Code: function MM_changeProp(objId,x,theProp,theValue) { //v9.0 var obj = null; with (document){ if (getElementById) obj = getElementById(objId); } if (obj){ if (theValue == true || theValue == false) eval("obj.style."+theProp+"="+theValue); else eval("obj.style."+theProp+"='"+theValue+"'"); } } function nextPhoto() { MM_changeProp('fanThumbWrapOne','','left','-195px','DIV') } function prevPhoto() { MM_changeProp('fanThumbWrapOne','','left','195px','DIV') } so where you see -195px and 195px in the functions for nextPhoto and prevPhoto I need those to actually be functions where it subtracts 195px or adds 195px. i have a program where a user enters a temperature in farenheit and the program converts it to celcius. below is my code: Code: <html> <head> <title>JavaScript Assignment 4 Part 1</title> </head> <body> <h2>Welcome to the Temperature Calculator!!</h2> <script type="text/javascript"> var fTemp; var number1; var cTemp; fTemp = window.prompt( "Please enter temperature in Farenheit:", "0" ); number1 = parseInt( fTemp ); cTemp = (5/9) * (number1 - 32); document.writeln("The corresponding temperature in Celcius is: " + cTemp); </script> </body> </html> what i cant figure out is how to round off the temperature in celcius so that it doesnt display something like 26.666666666667 i tried putting math.round in "cTemp = (5/9) * (number1 - 32);" but when i do my program doesnt work any advice on how to go about doing this? thanks |