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