Borrar filtros
Borrar filtros

Program not printing to a text file properly

2 visualizaciones (últimos 30 días)
TheSaint
TheSaint el 25 de Feb. de 2024
Respondida: Voss el 25 de Feb. de 2024
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.

Respuesta aceptada

Voss
Voss el 25 de Feb. de 2024
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.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by