如何將來自用戶的輸入存儲在數組中。那麼在C++中,我們必須在使用之前定義數組,或者必須爲未知大小分配動態內存。但是在這個程序中,當我從數組中的用戶獲取輸入時,它將最後輸入的值存儲爲非全部值。我該怎麼辦。Matlab數組處理
for x=1:1:2
f=input('Please enter the frequency for Sinusoid Graph');
freq=[f];
end
disp(freq)
如何將來自用戶的輸入存儲在數組中。那麼在C++中,我們必須在使用之前定義數組,或者必須爲未知大小分配動態內存。但是在這個程序中,當我從數組中的用戶獲取輸入時,它將最後輸入的值存儲爲非全部值。我該怎麼辦。Matlab數組處理
for x=1:1:2
f=input('Please enter the frequency for Sinusoid Graph');
freq=[f];
end
disp(freq)
編輯:
我認爲tmpearce有它收入囊中,對不起,我誤會了,我第一次看着它。我正在糾正我的答案,但它會像tmpearce那樣看起來很多。
% preallocate array
freq = zeros(1,2);
for x=1:1:2
% prompt user for input
f=input('Please enter the frequency for Sinusoid Graph');
% make sure something got entered
if(~isempty(f))
% save the data in your array
freq(x) = f(end);
else
% alert user about the problem and quit
disp('You did not enter a frequency!');
break;
end
end
disp(freq)
%pre-allocate a 2 element vector
num_inputs = 2;
freq=nan(1,num_inputs);
%iterate from the start to the end of your freq vector
for i=1:length(freq)
f=input('Please enter the frequency for Sinusoid Graph');
if(~isempty(f))
%if a value was input, store it in freq
freq(i) = f;
end
end
通過預分配數組您使事情更加有效,你也能更輕易改變你有多少價值,要求用戶輸入,因爲你只有在一個定義向量的長度地點。例如,您還可以添加一些輸入驗證,以確保數字回來。
任何其他方式。因爲我不知道你寫的這段代碼的基礎知識。其實我是初學者。 – scorpion 2012-02-27 16:22:26
@scorpion,np之間tmpearce和我更正的代碼,你應該坐在漂亮。 – macduff 2012-02-27 17:01:22