roberthsu2003 / cAndC-

51 stars 18 forks source link

請將以下程式改為有排名次: #51

Open roberthsu2003 opened 2 weeks ago

roberthsu2003 commented 2 weeks ago
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

typedef struct student {
  string name;
  int chinese;
  int english;
  int math;
} Student;

int main() {
  int min = 50;
  int max = 100;
  srand(time(NULL));
  int nums = 50;
  Student students[nums];
  for (int i = 0; i < nums; i++) {
    students[i].name = "學生" + to_string(i+1);
    students[i].chinese = rand() % (max - min + 1) + min;
    students[i].english = rand() % (max - min + 1) + min;
    students[i].math = rand() % (max - min + 1) + min;
  }

  for (int i = 0; i < nums; i++) {
    int sum = 0;
    cout << students[i].name << endl;
    cout << "國文:" << students[i].chinese << " ";
    cout << ",英文:" << students[i].english << " ";
    cout << ",數學:" << students[i].math << "\n";
    sum = students[i].chinese + students[i].english + students[i].math;
    cout << "總分:" << sum << endl;
    printf("平均:%.2lf\n\n", sum / 3.0);
  }
}

改為

學生15
國文:95 ,英文:75 ,數學:87
總分:257
平均:85.67
名次:1

學生25
國文:86 ,英文:93 ,數學:58
總分:237
平均:79.00
名次:2

學生8
國文:69 ,英文:97 ,數學:99
總分:265
平均:88.33
名次:3
Gin-4869 commented 2 weeks ago
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

// 定義結構
typedef struct student{
  string name;
  int chinese;
  int english;
  int math;
  int sum = 0; 
  double average;
}Student;

int main() {
  int n = 50;
  int min = 50;
  int max = 100;

  Student tmp;

  srand( time( NULL ) );
  // 建立結構變數
  Student students[n];
  for(int i = 0; i < n; i++){
    string name_ori = "學生" + to_string(i+1);
    students[i].name = name_ori;
    students[i].chinese = rand() % (max - min +1) + min;
    students[i].english = rand() % (max - min +1) + min;
    students[i].math = rand() % (max - min +1) + min;
    students[i].sum = students[i].chinese + students[i].english + students[i].math;
    students[i].average = students[i].sum / 3.0;
  }

  for(int i = 0; i < n; i++){
    for(int j = i + 1; j < n; j++){
      if( students[i].average < students[j].average ){
        tmp = students[i];
        students[i] = students[j];
        students[j] = tmp;
      }
    }
  } 

  for(int i = 0; i < n; i++){
    cout << "名次:" << i + 1 << endl;
    cout << students[i].name << endl;
    cout << "中文:" << students[i].chinese << " ";
    cout << "英文:" << students[i].english << " ";
    cout << "數學:" << students[i].math << "\n";
    cout << "總分:" << students[i].sum << "\n";
    printf("平均:%.2lf\n\n", students[i].average);
  }

}