【发布时间】:2015-09-12 23:43:35
【问题描述】:
我已经放弃了这个任务,但我已经保存了旧代码,所以如果有什么可以挽救的,我会全力以赴。
我现在有一个 do while 循环,它会重复两个问题,就像用户输入的一样多,而且效果很好。但是我不知道如何将最终数字加在一起,甚至更不知道如何让它们正确平均,这样我就可以把它们变成一个百分比。
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
//declare variables
int n = 0;
int counter = 0;
double score = 0.0;
double total = 0.0;
double avg = 0.0;
double scoreTotal = 0.0;
double totalTotal = 0.0;
//Prompt user for number of assignments
cout << "How many assignments are there? ";
cin >> n;
counter = 0;
do
{
counter++;
//prompt user for score */count up for each query*/
cout << "What is the score for assignment number " << counter << "? ";
cin >> score;
//prompt user for totals */count up for each total*/
cout << "What is the total score available for assignment number " << counter << "? ";
cin >> total;
}
while(counter < n);
//calculate averages
scoreTotal += score;
totalTotal += total;
avg = ((scoreTotal / totalTotal) * 100) / n;
//output how much it was out of and percent
cout << "Your total is " << scoreTotal << " out of " << totalTotal << ", or " << avg << "%" << endl;
return 0;
}
我只是猜测 avg 部分,但结果不正确,所以我知道那是错误的。
我的旧代码让它正确地结束循环周期,但它对新代码的影响很大,比如将计数器更改为仅偶数,并且它输出的提示比用户请求的提示高。
#include<iostream>
using namespace std;
int main()
{
float s; // assignment score
float t; // total points worth
float p; // percentage
int n;
//input the number of assignments
cout << "How many assignments are there? ";
cin >> n;
for (int i=1; i <=n; i++)
{
//input the total points earned for assignment
cout << "What is the score earned for this assignment? ";
cin >> s;
//input the number of points assignment is worth
cout << "How many points was the assignment worth? ";
cin >> t;
//calculate percentage
p = ((s / t) * 100) ;
p += i;
}
//output score
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "Total score: " << p << "%"<< endl;
return 0;
}
我的教科书也无济于事。它从解释 Do 和 Do While 循环跳到展示如何使用 For 循环,而没有任何关于它们的兼容性的解释。
任何帮助!谢谢!
【问题讨论】:
-
请直接解释赋值是什么,我们不需要从你的代码中推断出来。
-
我可以做得更好,我会复制并粘贴参数。
-
编写一个程序,以百分比形式计算 N 个课堂练习的总成绩。用户应输入 N 的值,然后输入 N 个分数和总数中的每一个。计算总百分比(获得的总分除以可能的总分。)并将其输出为百分比。示例输入和输出如下所示。输入多少练习? 3 锻炼 1 获得的分数:10 锻炼 1 可能获得的总分:10 锻炼 2 获得的总分:7 锻炼 2 可能获得的总分:12 您的总分是 30 分中的 22 分,即 73.33%
-
请编辑您的问题以包含此内容。
-
p += i这部分是什么意思?每次循环迭代都会为 s、t 和 p 的值分配新值,因此前一次迭代的数据会丢失。
标签: c++ sum average break do-while