What is the problem in my for loops?

1 visualización (últimos 30 días)
alexander wong
alexander wong el 23 de Jun. de 2021
Comentada: Scott MacKenzie 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', 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
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]);
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

Iniciar sesión para comentar.

Respuestas (2)

KSSV
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
alexander wong
alexander wong el 23 de Jun. de 2021
Do you know how to solve this problem?
Walter Roberson
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.

Iniciar sesión para comentar.


Scott MacKenzie
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
alexander wong
alexander wong el 23 de Jun. de 2021
Thank you so much.
Scott MacKenzie
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. :)

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by