What is the problem in my for loops?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
function tabulatedata()
m = input('Enter m: ');
n = input('Enter n: ');
p = input('Enter p: ');
fprintf('\nColumn 1\Column 2\n');
for i = 0:n:m
for j = 0:m/n
a = (2.^(j))*p;
fprintf('%3.2f\t\t\t', i);
fprintf('%3.2f\n', a);
end
end
end
We input m = 12, n = 2, p=100
Output:
Column1 Column 2
0.00 100.00
2.00 200.00
4.00 400.00
6.00 800.00
8.00 1600.00
10.00 3200.00
12.00 6400.00
I cannot get the correct output.
1 Kommentar
Stephen23
am 23 Jun. 2021
You don't need any loops:
m = 12;
n = 2;
p = 100;
v = 0:n:m;
a = 2.^(v./2)*p;
fprintf('%3.2f\t\t\t%3.2f\n', [v;a]);
Antworten (2)
KSSV
am 23 Jun. 2021
function tabulatedata()
m = input('Enter m: ');
n = input('Enter n: ');
p = input('Enter p: ');
fprintf('\nColumn 1\Column 2\n');
for i = 0:n:m
for j = 0:m/n
a = (2.^(j))*p;
fprintf('%3.2f\t\t\t %3.2f\n', i,a);
end
end
end
5 Kommentare
Walter Roberson
am 23 Jun. 2021
What problem? You said you do not get the right output, but you do not tell us what output you expect instead.
Scott MacKenzie
am 23 Jun. 2021
You don't need nested loops:
m = 12;
n = 2;
p = 100;
fprintf('\nColumn 1\t\tColumn 2\n');
for i = 0:n:m
a = 2.^(i/2)*p;
fprintf('%3.2f\t\t\t', i);
fprintf('%3.2f\n', a);
end
Output:
Column 1 Column 2
0.00 100.00
2.00 200.00
4.00 400.00
6.00 800.00
8.00 1600.00
10.00 3200.00
12.00 6400.00
2 Kommentare
Scott MacKenzie
am 23 Jun. 2021
You're welcome. BTW @Stephen Cobeldick's answer is clearly better. Feel free to unaccept my answer and choose @Stephen Cobeldick's answer. I won't take offence. :)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!