MATLAB 怎么分类输出 正负数

题目给出了20个未被分类的数,要求是对哪些是正数,哪些是负数进行分类,以及有多少正数,多少负数。要求的输出结果格式如图。求解答,追加悬赏。

1)数据的读入:从txt文件中读取数据

方法一:在文件目录下存储一个unsortedList.txt文件,(就是和处理该数据的程序的.m文件放在同一目录下即可)文件中输入原来未进行排序的数值,如图1所示。

图1 unsortedList.txt文件

方法二:随机生成一个1*20的数组,即unsortedList =round(rand(1,20)*100-50);并将该语句放在下面2)中的程序的load unsortedList.txt的位置即可。

2)将文件的数据导入MATLAB中并对其进行处理和在显示屏中输出(显示)。

MATLAB的处理代码如下所示:

%% input the unsorted numbers

load unsortedList.txt

number = size(unsortedList,2);

%% display unsorted numbers

fprintf('All 20 unsorted numbers:');

for index = 1:number

fprintf('%d',unsortedList(1,index));

fprintf(' ');

end

disp(' ');

%% Negatives

negIndex = find(unsortedList<0);

negNumber = size(negIndex,2);

negatives = unsortedList(1,negIndex);

negSum = sum(negatives);

% output

fprintf('%d',negNumber);

fprintf(' Negatives:');

for index = 1:negNumber

fprintf('%d',negatives(1,index));

fprintf(' ');

end

disp(' ');

fprintf('The sum of Negatives is ');

fprintf('%d',negSum);

disp(' ');

disp(' ');

%% Positives

posIndex = find(unsortedList<0);

posNumber = size(posIndex,2);

posatives = unsortedList(1,posIndex);

posSum = sum(posatives);

% output

fprintf('%d',posNumber);

fprintf(' posatives:');

for index = 1:posNumber

fprintf('%d',posatives(1,index));

fprintf(' ');

end

disp(' ');

fprintf('The sum of posatives is ');

fprintf('%d',posSum);

disp(' ');

disp(' ');

3)运行结果

备注:如果需要修改数组,或者输入多组数据,则在unsortedList.txt里面输入你的数组,且每一组数据之间用换行符(即Enter回车键)。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-04-04

程序代码如下:

有简化的余地:)运行结果:

追问

???

本回答被提问者和网友采纳
相似回答