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;
}
Related
Use for loops to process the data for 5 employees.
One loop to load the data
One loop to print the output.
In for loops, if any of the entered fields are –1, break out of the loop immediately after getting -1
Update the output as shown in the sample data.
Use arrays to store the user input.
I have a problem with breaking out of the loop. I think the system is reading it as an integer, not a character.
I also have a problem with looping the output. It is not looping the number of times the user has entered the info.
#include <stdio.h>
int main()
{
char name[5][10];
float hourswork[10];
float hourspay[10];
float grosspay[10];
float taxes[10];
float netpay[10];
int i = 0;
for (i = 0; i < 5; i++)
{
printf("Hello, enter your name: \n");
scanf("%s", &name[i][10]);
printf("Enter your hourly wage: \n");
scanf("%f", &hourspay[i]);
printf("Enter the hours you have worked \n");
scanf("%f", &hourswork[i]);
if (hourswork[i] <= 40)
{
grosspay[i] = hourspay[i] * hourswork[i];
}
else if (hourswork[i] > 40)
{
grosspay[i] = (40 * hourspay[i]) + (((hourswork[i] - 40) * 1.5) * hourspay[i]);
}
taxes[i] = grosspay[i] * 0.2;
if (name[i][10] == -1||hourspay[i] == -1||hourswork[i] == -1)
{
break;
}
}
for (i = 0; i < 5; i++)
{
printf("\n%c's Pay:\n", name[i][10]);
printf("Hourly Rate: %.2f\n", hourspay[i]);
printf("Hours Worked: %.2f\n", hourswork[i]);
printf("Gross Pay: %.2f\n", grosspay[i]);
printf("Taxes: %.2f\n", taxes[i]);
netpay[i] = grosspay[i] - taxes[i];
printf("Net Pay: %.2f\n\n", netpay[i]);
}
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 */
}
I am required to create a function that uses arrays and a menu system that displays:
the sum of all numbers entered, the average of numbers entered, and all numbers entered. It will allow the user to enter up to 1000 numbers.
I have the majority of the code working, I just need to figure out how to display all of the numbers a user has entered so far. Would anyone be able to help me with this? Thanks!
I've tried displaying the number entered, but this does not fit the assignment requirements.
Here is the code I have so far:
/*
Title: Array Intro
Author: James Henderson
Desc: a program designed to display the sume, average, and all previous numbers entered of user input numbers
Date: 11/06/19
*/
#include <stdio.h>
#include <math.h>
//Create Variables
//used for math
int counter = 0;
float number, sum = 0.0, average;
//user input number
int userInt;
int userInput[1000];
//Void Function
static void sumFunction(userInput)
{
printf("\n\tWelcome!\n");
printf("Enter 1 to begin:\n");
scanf("%i", &userInput);
//switch statement
while (1)
{
switch (userInput)
{
case 1:
printf("\nEnter a number:\n");
while (1)
{
scanf("%i", &userInput);
//determine sum
number = userInput;
sum += number;
counter++;
average = sum / counter;
printf("\n The average of the numbers is %.2f", average);
printf("\n The sum of the numbers is %.2lf", sum);
printf("\n You may enter up to 1000 numbers");
printf("\n You have entered %d numbers\n", counter);
if (counter == 1000)
{
printf("\nThank you for using my program! Have a lovely day :)");
return;
}
}
}
}
}
Your approach was right, just look how i used userInput. Below code works fine:
#include <stdio.h>
#include <math.h>
//Create Variables
//used for math
int counter = 0;
float number, sum = 0.0, average;
//user input number
int userInt;
int userInput[1000];
//Void Function
static void sumFunction()
{
printf("\n\tWelcome!\n");
printf("Enter 1 to begin:\n");
scanf("%i", &userInt);
//switch statement
while (1)
{
switch (userInt)
{
case 1:
printf("\nEnter a number:\n");
while (1)
{
scanf("%i", &userInput[counter]);
//determine sum
number = userInput[counter];
sum += number;
counter++;
average = sum / counter;
printf("\n The average of the numbers is %.2f", average);
printf("\n The sum of the numbers is %.2lf", sum);
printf("\n You may enter up to 1000 numbers");
printf("\n You have entered %d numbers\n", counter);
// number entered so far
printf("\n The list of numbers entered so far : \n");
for(int i=0;i<counter;i++){
printf(" %d ",userInput[i]);
}
printf("\n");
if (counter == 1000)
{
printf("\nThank you for using my program! Have a lovely day :)");
return;
}
}
}
}
}
int main(){
sumFunction();
}
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's my code:
#include <stdio.h>
int validate(int low,int high);
int main ()
{
//Declare Variables
float strength, speed, defense, intelligence;
float strengthRatio, speedRatio, defenseRatio, intelligenceRatio;
int strength_F, speed_F, defense_F, intelligence_F;
float sum;
int luck;
float PStrength=10;
float PDefense=20;
float PIntelligence=40;
int PHP=10;
float EStrength=30;
float EDefense=40;
float EIntelligence=25;
int EHP=10;
int sel;
float attackp;
float magicp;
int low=1;
int high=3;
int Valid_Selection;
//Clear Screen
system("cls");
//Display Logo
printf("+----------------------+\n");
printf("| |\n");
printf("| CODE QUEST |\n");
printf("| |\n");
printf("+----------------------+\n\n");
//Main Menu
printf("--Main Menu--\n");
printf("\n");
printf("1 - New Game\n");
printf("2 - Load Game\n");
printf("3 - Exit\n");
printf("\n");
printf("Selection: \n\n");
//Validate user input using a functuion
Valid_Selection = validate(int low,int high);
//Game_Selection = validate();
printf ("Character Creation \n");
printf ("Please enter your desired stats for your character:\n");
printf ("\n");
printf ("Enter strength: ");
scanf ("%f", &strength);
printf ("Enter speed: ");
scanf ("%f", &speed);
printf ("Enter defense: ");
scanf ("%f", &defense);
printf ("Enter intelligence: ");
scanf ("%f", &intelligence);
//Calculate the sum of all attributes
sum = strength + speed + defense + intelligence;
//Calculate ratios for each attribute
strengthRatio = strength / sum;
speedRatio = speed / sum;
defenseRatio = defense / sum;
intelligenceRatio = intelligence / sum;
//Calculate the final Stats as whole number
strength_F = strengthRatio * 100;
speed_F = speedRatio * 100;
defense_F = defenseRatio * 100;
intelligence_F = intelligenceRatio * 100;
//Calculate the player's luck
luck = (int)sum % 30;
//Create an empty line for beauty
printf ("\n");
//Display to the user the finalized player stats
printf ("Your player's final stats are:");
printf ("\n");
printf ("Strength: %d\n", strength_F);
printf ("Speed: %d\n", speed_F);
printf ("Defense: %d\n", defense_F);
printf ("Intelligence: %d\n", intelligence_F);
printf ("Luck: %d\n", luck);
//Display "Battle Starts"
printf("Battle Start!\n\n");
while (PHP>=0 && EHP>=0) {
//Display user and enemy HP and asks user which attack execute
printf("Your HP: %d, Enemy HP: %d\n", PHP, EHP);
printf("1 - Attack Power\n");
printf("2 - Magic Power\n");
scanf("%d",&sel);
//Option 1, Option 2
if (sel==1){
attackp = (PStrength/EDefense)*5;
EHP = EHP - attackp;
printf("You Attacked The Enemy\n");
}
else{
magicp = (PIntelligence/EIntelligence)*5;
EHP = EHP - magicp;
printf("You bewitched the enemy!\n");
}
//Enemy reaction based on his own HP
if (EHP<=0)
printf("You Won!\n");
else {
attackp = (EStrength/PDefense)*5;
PHP = PHP - attackp;
printf("The Enemy Attacked You\n");
}
//Indicates if user lost the game
if (PHP<=0)
printf("You Lost!\n");
printf("\n");
}
return 0;
}
int validate(int low, int high) {
int s;
do{
scanf("%d", s);
if (s<1 || s>3)
printf("innvalid Input, try again:");
} while (s<1 || s>3);
return s;
}
int validate(int low, int high) {
int selection;
do {
scanf("%d", selection);
if (selection <0 || selection>3)
printf("Invalid Input, try again: ");
} while (0<selection<4);
return selection;
}
I want the user to enter a number between 1 and 3 and I need the validate function to verify it. Can anyone explain me where I go wrong please? what is the proper way to do it?
Your validate must be called as:
//Validate user input using a functuion
Valid_Selection = validate(1, 3);
as your menu has choices between 1 and 3, and your function should be:
int validate(int low, int high) {
int s=0;
char buf[128];
do {
if (fgets(buf,128,stdin)==0 || sscanf(buf, "%d", &s)!=1 || (s<low || s>high))
printf("invalid Input, try again:");
else
return s;
} while (1);
}
and there can be only one function with that name, so remove the second one. Btw, while (0<selection<4) in the second one, must be written as: while (0<selection && selection<4).
Edit: note the check for the return value of sscanf. It tells us whether sscanf could read the value type specified, %d, and note to pass the address of the integer where to store the result. The initialization of s to zero ensures the while loop will not be exited while there was invalid input.
Edit: fixed Chux's comment to consume stdin.