how do i average numbers on matlab/octave using for loops and no arrays. Beginner programmer.
14 ビュー (過去 30 日間)
古いコメントを表示
My task is to ask the user how many numbers they will like to average in my case im setting it up so it will be 5 numbers. (I think this part should be only up to the user but i dont really know how to set this up correctly) Then i will ask then to "enter a number" repeatedly depending on the amount of numbers they chose to average. lastly, the command window will display to them " the average for the (amount they chose) numbers you entered is....." . sounds basic enough but this is what i came up so far and it doesnt seem to be going where i need it to be. how can i fix this?
user = input('How many numbers would you like to average? ');
for num = 1:5
input('Enter a number: ')
end
fprintf('The average of the 5 numbers you entered is %.2f\n',average)
0 件のコメント
回答 (1 件)
David Hill
2020 年 4 月 4 日
You were close, just a few mistakes.
user = input('How many numbers would you like to average? ');
for num = 1:user
a(num)=input('Enter a number: ');
end
fprintf('The average of the 5 numbers you entered is %.2f\n',mean(a));
1 件のコメント
Image Analyst
2020 年 4 月 4 日
Or, using the loop itself to compute the mean instead of the mean() function:
numNumbers = input('How many numbers would you like to average? ');
theSum = 0;
for k = 1: numNumbers
userPrompt = sprintf('Enter number %d (out of %d) : ', k, numNumbers);
a = input(userPrompt);
theSum = theSum + a;
end
average = theSum / numNumbers
fprintf('The average of the %d numbers you entered is %f.\n', numNumbers, average);
参考
カテゴリ
Help Center および File Exchange で Octave についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!