Antworten (2)

KSSV
KSSV am 18 Okt. 2017

0 Stimmen

str = '1+2+3+4=10' ;
fprintf('Result is:%s\n',str)

5 Kommentare

Mubashir Ali
Mubashir Ali am 18 Okt. 2017
Bearbeitet: Walter Roberson am 18 Okt. 2017
clc,clear
sum=0;
m=input('from:');
n=input('to:');
vec=zeros(m:n);
if m>n
disp('Invalid numbers')
end
fprintf('result is:\n');
for i=m:n
sum=sum+i;
fprintf('\%')
end
Mubashir Ali
Mubashir Ali am 18 Okt. 2017
dear i want to print summation of integers with in loop..
KSSV
KSSV am 18 Okt. 2017
for i=m:n
sum=sum+i;
fprintf('result is:%f\n',sum)
end
Walter Roberson
Walter Roberson am 18 Okt. 2017
Bearbeitet: Walter Roberson am 18 Okt. 2017
fprintf('%d+', m:n-1);
fprintf('%d = %d\n', n, TheTotal)
You definitely need to fix your vec array, whatever it is for. You are currently constructing a multidimensional array, such as zeros(2,3,4,5) for the case 2:5
Using 'sum' as the name of a variable is not recommended; it is quite common to try to use 'sum' as a variable name and then in the same code segment, try to call sum() as a function.
Jan
Jan am 18 Okt. 2017
Bearbeitet: Jan am 18 Okt. 2017
@Mubashir Ali: We had multiple questions in the forum concerning the redefinition of "sum" as a variable:
% Hidden in another script:
sum = rand(1, 10);
...
sum(1:100) % Why is this not working?
So better avoid using names of built-in function as variables. Use e.g. "s" instead.

Melden Sie sich an, um zu kommentieren.

Jan
Jan am 18 Okt. 2017
Bearbeitet: Jan am 18 Okt. 2017

0 Stimmen

This is a homework question, but you have shown an almost working code already. I only clean it up a little bit:
m = input('from:');
n = input('to:');
if m>n
error('Invalid numbers'); % not DISP: Never proceed after an error!
end
% vec=zeros(m:n); % Neither needed, but better: vec = zeros(m-n, 1);
fprintf('result is:\n');
s = 0;
for i = m:n
s = s + i;
if i < n
fprintf('%d + ', i);
else % In the last iteration display the result also:
fprintf('%d = %d\n', i, s);
end
end

Kategorien

Gefragt:

am 18 Okt. 2017

Bearbeitet:

Jan
am 18 Okt. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by