What is the problem in my for loops?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 23 de Jun. de 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]);
Respuestas (2)
KSSV
el 23 de Jun. de 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 comentarios
Walter Roberson
el 23 de Jun. de 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
el 23 de Jun. de 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 comentarios
Scott MacKenzie
el 23 de Jun. de 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. :)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!