I'm having trouble with the output of my program, the txt files show that the student got 3 answers wrong, but it keeps giving me 0% for percent of correct answers.
The challenge I was given is:
"One of your professors has asked you to write a program to grade her final exams,
which consist of only 20 multiple-choice questions. Each question has one of four possible answers: A, B, C, or D. The file CorrectAnswers.txt contains the correct answers for
all of the questions, with each answer written on a separate line. The first line contains
the answer to the first question, the second line contains the answer to the second question, and so forth.
Write a program that reads the contents of the CorrectAnswers.txt file into a char
array, and then reads the contents of another file, containing a student’s answers, into
a second char array.
The program should determine the number of questions that the student
missed, and then display the following:
• A list of the questions missed by the student, showing the correct answer and the
incorrect answer provided by the student for each missed question
• The total number of questions missed
• The percentage of questions answered correctly. This can be calculated as
Correctly Answered Questions ÷ Total Number of Questions
• If the percentage of correctly answered questions is 70% or greater, the program
should indicate that the student passed the exam. Otherwise, it should indicate
that the student failed the exam.
This is the code I have so far, thanks in advance for any suggestions!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int size=20;
static int count=0;
string correctAnswers[size];
string studentAnswers[size];
ifstream inFileC;
inFileC.open("c:/Users/levi and kristin/Desktop/CorrectAnswers.txt");
if (inFileC)
{
for (int i=0;i<20;i++)
{
inFileC>>correctAnswers[i];
}
}
else
{
cout<<"Unable to open \"CorrectAnswers.txt\""<<endl;
cout<<"Please check file location and try again."<<endl<<endl;
}
inFileC.close();
ifstream inFileS;
inFileS.open("c:/Users/levi and kristin/Desktop/StudentAnswers.txt");
if (inFileS)
{
for (int t=0;t<20;t++)
{
inFileS>>studentAnswers[t];
}
}
else
{
cout<<"Unable to open \"StudentAnswers.txt\""<<endl;
cout<<"Please check file location and try again."<<endl<<endl;
}
inFileS.close();
for (int k=0;k<20;k++)
{
if (correctAnswers[k]!=studentAnswers[k])
{
cout<<endl<<"Correct Answer: "<<correctAnswers[k];
cout<<endl<<"Student Answer: "<<studentAnswers[k]<<endl;
count++;
}
}
int percent=((20-count)/20)*100;
cout<<endl<<"Number of missed questions: "<<count;
cout<<endl<<"Percent of correctly answered questions: "<<percent<<"%";
if (percent>=70)
{
cout<<endl<<endl<<"********"<<endl<<"**Pass**"<<endl<<"********"<<endl<<endl;
}
else
{
cout<<endl<<endl<<"********"<<endl<<"**Fail**"<<endl<<"********"<<endl<<endl;
}
return 0;
}
Integer division will yield 0 for everything but a perfect score. Use floating-point division instead:
int percent = ((double)(20-count) / 20) * 100;
Note that (double)(20-count) casts the value (20-count) into a double-precision floating-point number. Once the whole expression has been evaluated, it gets coerced back to an integer because you're assigning the value to an int.
Integer divide always rounds towards zero, so (20 - count)/20 will be zero if count is greater than 0.
Do not need floating point, this will do the trick:
int percent = 5 * ( 20 - count );
Related
I find this very stupid to ask, but I've been trying a question on Google Kickstart (Round A, 2021).
Now, firstly, I'd like to clarify that I do NOT need help with the question itself, but I'm encountering a weird issue that seems to be compiler-related. This problem only arises on certain compilers.
I am posting the question link, then the question statement if someone does not wish to use the link, then the problem I'm facing along with the code that works and the code that doesn't work.
Question Title: K-Goodness String, Round A (2021)
Question Link: https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cca3
Problem
Charles defines the goodness score of a string as the number
of indices i such that Si ≠ SN−i+1 where 1≤i≤N/2 (1-indexed). For
example, the string CABABC has a goodness score of 2 since S2 ≠ S5 and
S3 ≠ S4.
Charles gave Ada a string S of length N, consisting of uppercase
letters and asked her to convert it into a string with a goodness
score of K. In one operation, Ada can change any character in the
string to any uppercase letter. Could you help Ada find the minimum
number of operations required to transform the given string into a
string with goodness score equal to K?
Input
The first line of the input gives the number of test cases, T. T
test cases follow.
The first line of each test case contains two integers N and K. The
second line of each test case contains a string S of length N,
consisting of uppercase letters.
Output
For each test case, output one line containing Case #x: y,
where x is the test case number (starting from 1) and y is the minimum
number of operations required to transform the given string S into a
string with goodness score equal to K.
Sample Input:
2
5 1
ABCAA
4 2
ABAA
Sample Output:
Case #1: 0
Case #2: 1
Explanation:
In Sample Case #1, the given string already has a goodness score of 1. Therefore the minimum number of operations required is 0.
In Sample Case #2, one option is to change the character at index 1 to B in order to have a goodness score of 2. Therefore, the minimum number of operations required is 1.
The issue:
The problem is fairly straightforward, however, I seem to be getting a wrong answer in a very specific condition, and this problem only arises on certain compilers, and some compilers give the correct answer for the exact same code and test cases.
The specific test case:
2
96 10
KVSNDVJFYBNRQPKTHPMMTZBHQPZYQHEEEQFQWOJHPHFBFXGFFGXFBFHPHJOWQFQEEEHQYZPQHBZTMMPHTKPQRNBYFFVDNXIX
95 7
CNMYPKORAUTSYETNXAZQZGBFSJJNMOMINYKNTMHTARUMDXAJAXDMURATHMTNKYNIMOMNJJSFBGZQZAXNTEYSTUAROKPKJCD
Expected Output:
Case #1: 6
Case #2: 3
The problem arises when I do NOT use std::cout.clear() at a very specific place in my code. Just printing the value of any random variable also seems to solve this issue, it doesn't necessarily have to be cout.clear() only. I'm pasting the codes below.
**Original Code (Gives incorrect answer):**
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) { current_goodness++; }
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Incorrect Result for original code:
Case #1: 6
Case #2: 6
Modified Code (With cout.clear() which gives correct answer):
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) {
current_goodness++;
}
cout.clear();
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Correct Result for modified code:
Case #1: 6
Case #2: 3
A few additional details:
This issue is NOT coming up on my local machine, but on Google Kickstart's Judge with C++17 (G++).
Answer for Case #2 should be 3, and NOT 6.
This issue does NOT come up if only the second test case is executed directly, but only if executed AFTER test case #1.
The issue is ONLY resolved if the cout.clear() is placed within the for loop, and nowhere else.
We don't necessarily have to use cout.clear(), any cout statement seems to fix the issue.
I know it's a long question, but given that a problem is only coming up on certain machines, I believe it would require a deep understanding of c++ to be able to understand why this is happening, and hence posting it here. I'm curious to understand the reasoning behind such a thing.
Any help is appreciated.
As pointed out by Paddy, Sam and Igor in the comments, here is the solution as I understand it:
The problem arises because char s[N] is NOT C++ standard, any variable length arrays, for that matter. That might cause a buffer overrun, and will write over memory outside of the array, causing all sorts of weird behaviour.
The best way to avoid these kinds of bugs is to make it logically impossible for them to happen. – Sam Varshavchik
In this case, using string s solved the issue without having to call cout.clear().
Also, using #define endl "\n" might be faster when redirecting output to files, but since we're importing the entire std namespace, any person who does std::cout will get an error because it'll essentially get translated to std::"\n" which does not make sense.
I'm new too c++ and I had to design a program that determines the first four triangular square numbers and the output is exactly how I want it to be, but it wont quit after its printed the first four. I can't figure out what it could be. I can't CTRL C because I will get points taken off. What is the issue here?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Prints name line
cout<<"*********** BY: ********"<<endl;
//Initializing
const int HOW_MANY=4;
int num=1;
int tsn=0;
int z=1;
int x=0;
//How many TSN it will find and be printed
while (x<=HOW_MANY)
{
//
int sum=0;
for (int y=0;y<512;y++)
{
sum+=y;
tsn=pow(num,2);
//Tests if the numbers are TSN
if ((sum==tsn) || (num+1)/sqrt(num)==sqrt(num))
{
//Prints 1-HOW_MANY TSN and what they are
cout<<"Square Triangular Number "<< z <<" is: "<< tsn <<endl;
z++;
x++;
}
}
num++;
}
return 0;
}
If x = 0 then instead of while (x<=HOW_MANY) you need write while (x<HOW_MANY).
x begins at 0. Every time you find and print a number it gets incremented. You'll continue this, so long as x<=HOW_MANY.
You say your program finds 4 numbers but keeps running. After 4 hits, x will be 4. Is 4 <= 4? The answer is yes, so your program keeps running.
Either change the condition to x < HOW_MANY, or initialize x to 1.
EDIT
Did a little leg work, it turns out the sum of all the numbers in the range [1,512] is 131328. The 5th square triangle number is 1413721.
This means after you find the fourth triangle number, you will never sum high enough to find the next one. This will result in the infinite loop you're seeing.
The answer above is still the correct fix, but this is the reason you end up with an infinite loop.
for should be used for iteration and while should be used for condition testing.
The problem, as has been noted, is that your x condition variable is never being incremented to get you out of the outer loop. That's a logic error that can be avoided by using the appropriate control structure for the job.
I have a test in a couple of days and I was reviewing the study guide and I came across a question that I wasn't familiar with. It says "Write a while loop that continuously loops until the user inputs a number saved in a variable named myNum between -1 and -100. Use only < and > operators." Can someone give me a clear explanation of what exactly I am supposed to do for this question?
I'm honestly not entirely sure what this question is asking, because it seems a bit ambiguous in the wording, but this is what I would assume they are asking for. I'm not sure how you could get this done with "only" > and < operators, as you need input and possibly output operators (>> and << respectively). Anyway, I hope that this helps, and if its not perfectly correct with what your assignment is, maybe you can see the logic and make the small changes to have it fit better.
I commented each line, even the obvious (which is sort of a no-no when you get into heavier coding), this way all the syntax makes sense.
#include <iostream>
using namespace std;
int main()
{
// Initialize myNum to 1 so that it passes into while-loop
int myNum = 1;
// Continue looping as long if number is less than -100 or greater than -1 (terminating the loop when numbers from -100 to -1 are entered)
while((myNum > -1) || (myNum < -100))
{
// Display "Enter Text" to console
cout << "Enter number: ";
// Allow user to input number
cin >> myNum;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}
As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.
I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".
I'm new in C++, I have a small project,
I should get 10 numbers from user and then show in result.
so I wrote this code :
#include<stdio.h>
int main() {
int counter=1,
allNumbers;
float score;
while(counter <= 10) {
scanf("%f",&score);
counter++;
}
printf("Your entered numbers are : %s\n",allNumber);
}
for example user enter 2 3 80 50 ... and I want show 2,3,80,50,... in result.
But I don't know what should I do !
I do not know what book you are using, but the authors appear to teach you C before going into the C++ land. Without discussing their motives, I'll write an answer to be similar to your style of code before discussing an ideal C++ solution.
You need an array to store your numbers: double score[10]
Array are indexed starting from zero, so change counter to start at zero and go to nine (instead of starting at one and going to ten, like you have now)
Since score is an array, use &score[count] in the call of scanf
To print ten numbers you need a loop as well. You need a flag that tells you whether or not you need a comma after the number that you print. Add a printf("\n") after the loop.
As far as an "ideal" C++ solution goes, it should look close to this one:
istream_iterator<double> eos;
istream_iterator<double> iit(cin);
vector<double> score;
copy(iit, eos, back_inserter(score));
ostream_iterator<double> oit (cout, ", ");
copy(score.begin(), score.end(), oit);
However, discussing it would remain hard until you study the C++ standard library and its use of iterators.
You can do it by declaring an array of ten numbers.
your code goes here:
#include <stdio.h>
int main() {
int counter=0;
float allNumbers[10];
while(counter < 10) {
scanf("%f",&allNumbers[counter]);
counter++;
}
printf("Your entered numbers are : \n");
counter=0;
while(counter < 10) {
printf("%f , ",allNumbers[counter]);
counter++;
}
}