I need help fixing my code. What my code does it asking users to input a number multiple times and will terminate the program once -1 is entered. Then, will get the Sum, Max, Min, Average and Median values.
Sum, Min and Max seems to be working fine. But on the "Average" it's treating the -1 as a userinput, also, I need help on how to get the median value.
Here's what I got so far.
#include <stdio.h>
int main(){
char name[30];
int userInput;
int count = 0;
int sum = 0; // changed from 1 to 0
int max, min = 1000;
float average;
printf("Please enter your name: ");
scanf("%s", &name);
printf("Hello, %s, ", name);
do {
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if (userInput == -1) break; // I added this line, average works fine now
sum = sum + userInput;
count = count + 1;
average = sum / count;
if (userInput > max){
max = userInput;
}
if (userInput < min && userInput >= 0){
min = userInput;
}
}
while (userInput >= 0);
printf("Sum: %d \n", sum);
printf("Average: %.2f \n", average);
printf("Max: %d \n", max);
printf("Min: %d \n", min);
return 0;
}
Here's my sample output:
Please enter your name: A
Hello, A, Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): 20
Enter an integer (-1 to quit): 10
Enter an integer (-1 to quit): -1
Sum: 40
Average: 10.00
Max: 20
Min: 10
So The rest seems to be working now after some modification except for getting the median value.
You do not want to increment the count when userInput == -1
You're incrementing the count and adding to the sum before checking whether userInput == -1. Try rewriting your loop:
while(1){
printf("Enter an integer (-1 to quit): ");
scanf("%d", &userInput);
if(userInput == -1)
break;
/* rest of loop body goes here */
}
Related
I have the following code and every time i run it, I get an extra count. Say for example that I input 8 first round and then a 2 next round and exit with the sentinel -1, the sum will be 10 as expected, but the count will be 3. I've debugged the program and no matter if count comes before the scanf() or after, I still get a 3 value. One possible solution is to initialized count to -1. However, I feel I shouldn't have to and setting count equal to zero should work. Do I have to set count to -1?
#include <stdio.h>
void calculateAverage()
{
int grade = 0, count, sum = 0;
double average;
count = 0;
while(grade != -1)
{
sum += grade;
count++;
printf("input a grade: \n");
scanf("%d", &grade);
}
average = (double)(sum)/(double)(count);
printf("%.2lf", average);
return;
}
int main( )
{
while (1)
calculateAverage();
return 0;
}
For starters there is no great sense to declare the variable sum as having the type int because in any case you are casting it to the type double
average = (double)(sum)/(double)(count);
You are increasing the variable count before the user will enter something.
The function can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void calculateAverage( void )
{
const int Sentinel = -1;
size_t count = 0;
double sum = 0.0;
printf( "input a grade (%d - stop): ", Sentinel );
for ( int grade; scanf( "%d", &grade ) == 1 && grade != Sentinel; )
{
sum += grade;
++count;
printf( "input a grade (%d - stop): ", Sentinel );
}
double average = count == 0 ? sum : sum / count;
printf( "%.2lf", average );
}
int main(void)
{
calculateAverage();
return 0;
}
The program output might look like
input a grade (-1 - stop): 1
input a grade (-1 - stop): 2
input a grade (-1 - stop): 3
input a grade (-1 - stop): 4
input a grade (-1 - stop): 5
input a grade (-1 - stop): 6
input a grade (-1 - stop): 7
input a grade (-1 - stop): 8
input a grade (-1 - stop): 9
input a grade (-1 - stop): 10
input a grade (-1 - stop): -1
5.50
You are incrementing count just before you enter -1. So, it counts -1 as well. Just in increase is if it's not -1.
#include <stdio.h>
void calculateAverage()
{
int grade = 0, count = 0, sum = 0;
double average;
while (grade != -1)
{
sum += grade;
printf("input a grade (-1 - stop): ");
scanf("%d", &grade);
if (grade != -1) // Check this line
count++;
}
average = (double)sum / count;
printf("%.2lf\n", average, sum, count);
return;
}
int main()
{
while (1)
calculateAverage();
return 0;
}
I'm currently trying to create a C program for a class assignment that takes the average of an arbitrary amount of test scores. However, I've run into some problems.
My professor has provided an outline to help get started. I also can only add code where indicated, so no extra variables and such.
This is what I have so far:
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (sum / count);
printf("average is %.2lf \n", &average);
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
So the problem I've ran into is that with what I have so far, the average will always be calculated as 0. Why exactly is this happening, and how would I fix it so it gives me the correct average?
UPDATE
So I tried casting the average to double so I can avoid a type mismatch, which did get rid of my compiler warnings but the average is still coming out to 0 for all inputed values.
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (double)(sum / count);
printf("average is %.2f \n", &average);
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
/* add code to input grades, calculate average, and print it */
/* --> between here */
printf("Enter the amount of test scores.\n");
scanf("%d", &count);
grade = 0;
sum = 0;
while (grade != -1 && grade <= 100 && grade >= 0)
{
printf("Enter the grade. Enter -1 when you are done entering grades.\n");
scanf("%d", &grade);
if (grade != -1 && grade <= 100 && grade >= 0)
{
sum = sum + grade;
}
else
{
average = (double)(sum / count);
printf("average is %.2lf \n", average); # <---- Please fix this!
}
}
/* --> and here */
}
int main(void)
{
while (1)
calculateAverage();
return 0;
}
There are a few problems in your code:
One is you are printing the address of average using & operator.
Another thing you can change is to use the correct format specifier when printing double.
Here I have created a compounding interest calculator. The user inputs principal, interest% and duration (in quarters). I have used a for loop for the initial calculation. But, I don't know how to get the total to rollover to the next quarter's principal.
Say the user inputs 1000, 5% and 2 quarters. The output should look like, Q1 Principal=$1000, Interest=0.05, Total=$1012.50, Q2 =$1012.50 =0.05 =$1025.16
Also my last Do while is giving me some issues. The ouput is spitting out a couple extra lines before letting the user start over.
Any advice would be greatly appreciated.
Thank you
#include <stdio.h>
int main (void)
{
int a = 0, b=0;
double interest, prin, total=0;
char check = ' ';
do{
do{
do{
printf (" Please enter principal:\n");
scanf ("%lf", &prin);
}while(prin <=0);
do{
printf ("Please enter desired interest greater
than 0 less than 20 :\n");
scanf ("%lf", &interest);
}while(interest <=0 || interest >20);
interest = interest/100;
do{
printf ("For how many quarters would you like
to deposit: (more than 0, less than 40) \n");
scanf ("%d", &b);
}while(b <=0 || b >40);
printf ("Is this information correct? Press X
to continue" );
scanf ("\n%c", &check);
}while(check != 'x' && check != 'X');
total = prin * (1+(interest *.25));
printf ("Quarter Principal Interest
Total\n");
for(a=1; ;++a){
printf ("%2d $%.2f %.2lf
$%.2lf\n", a, prin, interest, total);
if(a == b)
break;
}
printf ("Do you want to start over (Y/N)?");
scanf ("%c\n", &check);
}while(check != 'y' || check != 'Y');
return 0;
}
The are some problem with indentation and logic in your code. You need to updade principle in for loop statement. Then print it out .Here is my solution
#include <stdio.h>
int main(void)
{
int a = 0, b = 0;
double interest, prin, total = 0;
char check = ' ';
do {
do {
do {
printf(" Please enter principal:\n");
scanf("%lf", &prin);
} while (prin <= 0);
do {
printf("Please enter desired interest greater than 0 less than 20 :\n");
scanf("%lf", &interest);
} while (interest <= 0 || interest > 20);
interest = interest / 100;
do {
printf("For how many quarters would you like to deposit : (more than 0, less than 40) \n");
scanf("%d", &b);
} while (b <= 0 || b > 40);
printf("Is this information correct? Press X to continue" );
scanf("\n%c", &check);
} while (check != 'x' && check != 'X');
printf("Quarter Principal Interest Total\n");
for (a = 1; a<=b; ++a) {
total = prin * (1 + (interest *.25));
printf("%2d $%.2f %.2lf $%.2lf\n", a, prin, interest, total);
prin = total;
}
printf("Do you want to start over (Y/N)?");
scanf("%c\n", &check);
} while (check != 'y' || check != 'Y');
return 0;
}
I have written a program that asks the user the input the high and low temperature over the course of four days. Following this, the program calculates the mean temperature using the inputs from all four days. Everything is working fine however, I need to have the program determine and output the greatest high temperature and the day it occurred on as well as the smallest low temperature and the day it occurred on. Here's my code so far
#include <stdio.h>
#define NUMS 4
int main (void)
{
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int totalhigh;
int totallow;
int sum;
float avg;
printf ("---===IPC Temperature Analyzer ===---\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
while (high[0] > MAX || low[0] < MIN || high[0] < low[0]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 1: ");
scanf ("%d", &high[0]);
printf ("Enter the low value for day 1: ");
scanf ("%d", &low[0]);
}
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
while (high[1] > MAX || low[1] < MIN || high[1] < low[1]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 2: ");
scanf ("%d", &high[1]);
printf ("Enter the low value for day 2: ");
scanf ("%d", &low[1]);
}
printf ("Enter the high value for day 3: ");
scanf ("%d", &high[2]);
printf ("Enter the low value for day 3: ");
scanf ("%d", &low[2]);
}
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
while (high[3] > MAX || low[3] < MIN || high[3] < low[3]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day 4: ");
scanf ("%d", &high[3]);
printf ("Enter the low value for day 4: ");
scanf ("%d", &low[3]);
}
totalhigh = high[0] + high[1] + high[2] + high[3];
totallow = low[0] + low[1] + low[2] + low[3];
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
if (high[0] > high[1] || high[0] > high[2] || high[0] > high[3]) {
printf ("The highest temperature was %d, on day 1\n", high[0]);
}
else if (high[1] > high[0] || high[1] > high[2] || high[1] > high[3]) {
printf ("The highest temperature was %d, on day 2\n", high[1]);
}
else if (high[2] > high[0] || high[2] > high[1] || high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
return 0;
}
Your current code can use a loop and a helper function, which would shorten your code by reducing all those scanf() calls. You could also abstract a lot more, by using more functions, but it will show the general idea.
It is also good to check the result of scanf(), just in case the user enters a non-integer.
Your current code could look like this:
#include <stdio.h>
#include <stdlib.h>
#define NUMS 4
/* takes a pointer to a number */
void get_input(int *temp) {
if (scanf("%d", temp) != 1) {
printf("Invalid temp entered\n");
exit(EXIT_FAILURE);
}
}
int main(void) {
int high[NUMS];
int low[NUMS];
const int MAX = 40;
const int MIN = -40;
int day = 1, totalhigh = 0, totallow = 0, sum;
float avg;
for (size_t i = 0; i < NUMS; i++) {
printf ("Enter the high value for day %d: ", day);
/* takes the address of the pointer given by get_input() */
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
while (high[i] > MAX || low[i] < MIN || high[i] < low[i]) {
printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
printf ("Enter the high value for day %d: ", day);
get_input(&high[i]);
printf ("Enter the low value for day %d: ", day);
get_input(&low[i]);
}
day++;
}
for (size_t i = 0; i < NUMS; i++) {
totalhigh += high[i];
totallow += low[i];
}
sum = totalhigh + totallow;
avg = sum/8.0;
printf ("The average (mean) temperature was: %.2f\n", avg);
return 0;
}
In terms of finding the largest and smallest temperatures, here is a method you can use:
Set max and min to the first element of your array, array[0].
loop from i=1 to i=n.
If and element if bigger than max, set max to array[i]. If an element is smaller than min, set min to array[i].
The day for the highest and lowest temperatures will be i+1.
Since doing something like this will help you understand loops better, I decided to just describe the steps. The above code was just an improvement on your current code, and showing you a easier way to do it will show you a different perspective on how to do problems like these.
I updated my code to have the if statement mentioned in my above code to function correctly. Here it is:
if (high[0] > high[1] && high[0] > high[2] && high[0] > high[3]) { // Check to see if day 1 has the highest temperature against days 2,3 and 4.
printf ("The highest temperature was %d, on day 1\n", high[0]); // Output day 1 as the highest temperature and indicate the temperature value.
}
else if (high[1] > high[0] && high[1] > high[2] && high[1] > high[3]) { // Same function as the above function for day 1 except this is used for day 2.
printf ("The highest temperature was %d, on day 2\n", high[1]); // Refer to day 1 printf
}
else if (high[2] > high[0] && high[2] > high[1] && high[2] > high[3]){
printf ("The highest temperature was %d, on day 3\n", high[2]);
}
else {
printf ("The highest temperature was %d, on day 4\n", high[3]);
}
// Switch out high values with low values in order to determine lowest temperature and its corresponding day.
In my program I'm messing around with, it simply asks for how many tests one has written and then returns an average. However I've modified it a bit so that it asks if the marks entered are correct.
Problem 1: It doesn't let you input your marks for all your tests
Problem 2: If the marks are wrong it starts over but keep the previous inputs in it's memory? How do I fix the?
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 1; //Loop counter to start from one
//---------------------------------------------------------------------------------------------------//
printf ("Please enter amount of test you've written so far: ");
scanf ("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
for(counter = 0; counter <= userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf ("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
} else {
fail = fail + 1;
}
}//end of for loop
printf ("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf ("%d", &yesNo);
if (yesNo == 2) {
} else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf ("\nYou are below sub minimum!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else if (average >= 75){
printf ("\nYou have a distinction agregate!\n");
printf ("Your overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
} else {
printf ("\nYour overall average is: %.2f %\n", average);
printf ("Passed: %d\n", pass);
printf ("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch ();
return 0;
}
In your do while loop, when you come around for your second pass you need to reset your variables. Specifically the total variable should be reset to zero. You do it for the first time outside the do while loop but once it's in the loop for the second pass it doesn't get reset to 0.
As for not reading all test inputs, if it asks for 9 but you need 10 then it likely is a problem with the for loop. I typically use counter++ and not ++counter as it increments the counter after the operation and not before the operation. That may or may not be the reason as I did not run your code, but it is worth looking at.
I've edited your code and commented the changes:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
//int variables for grade
unsigned int counter; //number of grades to be entered next
int grade;
int total;
float average;
// user input
int userInput; // amount of tests
int yesNo;
//amount of test passed
unsigned int pass = 0;
unsigned int fail = 0;
int doCount = 1;
//unsigned int test;
//---------------------------------------------------------------------------------------------------//
//standards for program to abide to
total = 0; //Total amount of test to be set to zero, until while statement
counter = 0; //Loop counter to start from zero, It's always better to start from zero
//---------------------------------------------------------------------------------------------------//
printf("Please enter amount of test you've written so far: ");
scanf("%d", &userInput);
//printf ("%d", userInput);
//---------------------------------------------------------------------------------------------------//
do {
//Body of calculations of program
total = 0; //You need to reset total pass and fail
pass = 0;
fail = 0;
for (counter = 0; counter < userInput; ++counter) { //for loop that correlates to userInput for amount of passes and test marks
printf("Please enter percentage mark: "); //prompt for test mark
scanf("%d", &grade);
total = total + grade;
//counter = counter + 1; You DON't need that
if (grade >= 40) { //if statement for pass or fail
pass = pass + 1;
}
else {
fail = fail + 1;
}
}//end of for loop
printf("Are the grades entered correct? (1 = yes, 2 = no): "); // user input for yesNo - are inputs correct
scanf("%d", &yesNo);
if (yesNo == 2) {
}
else {
average = ((float)total / userInput); //Getting average for tests so far
//if statement to clarify if you're passing
if (average < 40) {
printf("\nYou are below sub minimum!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else if (average >= 75) {
printf("\nYou have a distinction agregate!\n");
printf("Your overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
else {
printf("\nYour overall average is: %.2f %\n", average);
printf("Passed: %d\n", pass);
printf("Failed: %d", fail);
}
doCount = 2;
}
} while (doCount == 1);
average = ((float)total / userInput); //Getting average for tests so far
//---------------------------------------------------------------------------------------------------//
getch();
return 0;
}