C++程式:求解保持75%出勤率所需最少上課次數
在這個問題中,我們得到兩個數字M和N,分別表示截止到目前為止已上課的總次數和學生已上的課的次數。我們的任務是建立一個C++程式,來計算為了保持75%的出勤率所需最少上課次數。
問題描述
保持75%的出勤率是大學生們最關心的問題之一。本程式計算學生為了達到75%的出勤率而需要定期參加的最少課程次數。
讓我們來看一個例子來理解這個問題:
示例1
輸入:M = 32, N = 20
輸出: 16
解釋
為了達到至少75%的出勤率,學生必須至少再上16節課。這樣總課程數為48,已上課程數為36。
百分比 = 36*100/48 = 75%
示例1
輸入:M = 14, N = 4
輸出: 26
解釋
為了達到至少75%的出勤率,學生必須至少再上26節課。這樣總課程數為40,已上課程數為30。
百分比 = 30*100/40 = 75%
解決方案
這裡,我們需要找到學生需要上的課程數量。一種簡單的方法是在兩邊都加一節課,當除法結果大於等於0.75時停止新增並返回迭代器的值。
程式演示了我們解決方案的工作原理:
示例
#include <iostream>
using namespace std;
int maintainAtt(int M, int N) {
int att = 0; while(1){
if(((N+att)*100)/(M+att) >= 75){
return att;
}
att++;
}
}
int main() {
int M = 23, N = 12;
cout<<"The total number of lectures to be attended is "<<maintainAtt(M, N);
return 0;
}輸出:
The total number of lectures to be attended is 21
這種方法使用迴圈,使得解決方案的時間複雜度為O(n)。但是我們可以使用數學公式來計算次數,從而達到O(1)的時間複雜度。
保持75%出勤率所需最少上課次數的公式為
$$\square\square\square\square\left(\frac{(0.75M-N)}{0.25}\right)$$
程式演示了我們解決方案的工作原理:
示例
#include <iostream>
#include <math.h>
using namespace std;
int maintainAtt(int M, int N) {
int att = ceil(((0.75*M) - N)/(0.25)); return att;
}
int main() {
int M = 30, N = 11;
cout<<"The total number of lectures to be attended is "<<maintainAtt(M, N);
return 0;
}輸出
The total number of lectures to be attended is 46
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP