Given two decimal numbers as strings of arbitrary length, multiply them.
[Exercise] Decimal multiplication
import javax.swing.JOptionPane;
public static Multiply{
public static void main{
double num1;
double num2;
num1=Double.parseDouble(JOptionPane.showInputDialog("Enter first decimal");
num2=Double.parseDouble(JOptionPane.showInputDialog("Enter second decimal");
JOptionPane.showMessageDialog(null, "num1 * num2 = " + num1*num2);
}
}
Lamest? :)) havent tested but wtf it should work@eurybaric the aim of the exercise(most probably) is to actually implement an algorithm that converts the string into a decimal. i.e. something similar to what goes under the hood inside the parseDouble() function.
Or else would be too trivial to post as an exercise.
Or else would be too trivial to post as an exercise.
@eurybaric: Obviously, you cannot rely on the fact that your language already has float (or double) arithmetic. Use only int/long and strings.
Here's my code so far:
I'll be updating this soon after work.
Here's my code so far:
import sys
def f(s):
a = s.find('.')
return (int(s[:a]+s[a+1:]), len(s)-(a+1))
tot=1
dec=0
for i in map(f, sys.argv[1:]):
tot *= i[0]
dec += i[1]
stot = str(tot)
slen = len(stot) - dec
print stot[:slen] + "." + stot[slen:]
It (kinda) works:
It's very rudimentary, and will probably break on any input slightly more complex than the given example. (It breaks if the input string doesn't have a dot in it...).$ ./dec_mult.py 3.1 12.1
37.51
I'll be updating this soon after work.