Hello! I am trying to use a function in a script file to solve a word problem. I have most of the function within the script working but in order for it to work I have to repeat input values inside the function and then prior to calling the function. Is there a way I can eliminate this so the user does not have to type their answer multiple times? The code I have so far is below. Thank you!
while 1 %so there is an unlimited number of runs
gallons=input('Enter how many gallons of gas you need: '); priceA=input('Enter the price of gas at Station A: '); priceB=input('Enter the price of gas at Station B: '); Cost(gallons,priceA,priceB) %calling the function
mpg=input('\nEnter the miles per gallon your car gets: '); distance=input('Enter the distance between Station A and Station B: '); B=(distance/mpg)*(priceB); %used to find the amount of money spent traveling to Station B
Total_B=B+(gallons*priceB); %Add to the total spent on gasoline
Savings=(gallons*priceA)-Total_B; %used to find if the user is saving money by subtracting the 2 prices if negative they are losing money
if Savings>0 %positive savings
fprintf('\n Getting gasoline from Station B saves you $%f\n',Savings) elseif Savings==0 fprintf('\n There is no cost difference\n') else %losing money
fprintf('\n Buying gasoline from Station A is cheaper\n') endfunction [totalA, totalB]=Cost(gallons, priceA, priceB);gallons=input('Enter how many gallons of gas you need: ');priceA=input('Enter the price of gas at Station A: ');priceB=input('Enter the price of gas at Station B: ');totalA=gallons*priceA;fprintf('\n To buy %d gallons of gas at Station A it would cost $%2.2d\n',[gallons,totalA])totalB=gallons*priceB;fprintf('\n To buy %d gallons of gas at Station B it would cost $%d\n',[gallons,totalB])end
Best Answer