필터 지우기
필터 지우기

Program not printing to a text file properly

조회 수: 2 (최근 30일)
TheSaint
TheSaint 2024년 2월 25일
답변: Voss 2024년 2월 25일
read = importdata("testscores.txt");
StudentID = read(:,1);
Score = read(:,2);
fid = fopen('FinalGrades.txt', 'w');
FinalGrades = read(:,2);
LowScore = min(FinalGrades);
HighScore = max(FinalGrades);
AverageScore = mean(FinalGrades);
StandardDeviation = std(FinalGrades);
TotalA = 0;
TotalB = 0;
TotalC = 0;
TotalD = 0;
TotalF = 0;
fprintf("Here is a summary of all the scores \n")
fprintf("The lowest score in the class was a %0.1f. \n", LowScore)
fprintf("The highest score in the class was a %0.1f\n", HighScore)
fprintf("The average score of the entire class was %0.1f \n", AverageScore)
fprintf("The standard deviation of all the scores was %0.3f \n", StandardDeviation)
StudentID = read(1);
Score = read(2);
Grades = cell(size(Score));
for i = 1:numel(Score);
if Score(i) >= AverageScore + 1.5 * StandardDeviation
Grades{i} = 'A';
elseif Score(i) >= AverageScore + 0.5 * StandardDeviation
Grades{i} = 'B';
elseif Score(i) >= AverageScore - 0.5 * StandardDeviation
Grades{i} = 'C';
elseif Score(i) >= AverageScore - 1.5 * StandardDeviation
Grades{i} = 'D';
else
Grades{i} = 'F';
end
end
fid=fopen("FinalGrades.txt", "w");
for i = 1:numel(StudentID);
fprintf(fid, '%d\t%s\n', StudentID(i), Grades{i});
end
I have this code, which is supposed to read a bunch of data from a .txt file, then determine which student by student ID got what letter grade. It seems to work fine up until the point where I need it to print the table of Student IDs and letter grades to a new text file. When that occurs, it only prints one line of 1 student ID and 1 letter grade. Not sure what is going wrong.

채택된 답변

Voss
Voss 2024년 2월 25일
At first you make StudentID and Score column vectors
StudentID = read(:,1);
Score = read(:,2);
and later you overwrite those to be scalars
StudentID = read(1);
Score = read(2);
That's why it's only outputting a single ID and grade. Remove the second definition and stick with the first.
Also, you're opening the file with fopen two times. Just open it once, and don't forget to fclose it when you're done.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by