I am unable to get the input to be added and get the correct output for the average.
The code below is as far as I have made it. Any help would be greatly appreciated!
#include <stdio.h>
int main() {
/* variable definition: */
int days;
float avg, miles;
/* Initialize */
days=1;
// Loop through to input values
while(days<=7) {
printf("Enter the number of miles for each day walked.");
// use %lf for double, %f for float
scanf("%f", &miles);
days++;
}
avg = miles / days;
printf("average is %f\n " , avg );
return 0;
} // end main
As John3136 said, you aren't keeping track of the total miles walked. You scan in miles, but you don't keep track of the sum of the miles. Your average is simply your last entered miles divided by 7.
Here is a proposed solution:
int main(void)
{
// variable definition
int days = 0;
float avg = 0, miles = 0;
// Loop through to input values
while(days < 7)
{
printf("Enter the number of miles for each day walked: ");
scanf("%f", &miles);
avg += miles;
days++;
}
avg /= days;
printf("average is %.2f\n " , avg);
return 0;
}
With help from Jonathan Leffler here is an enhanced version of the previous code:
#include <stdio.h>
int main(void)
{
// variable definition
int days = 0;
double miles = 0.0, total_miles = 0.0;
// Loop through to input values
while(days < 7)
{
printf("Enter the number of miles for day %d: ", days + 1);
if(!scanf("%lf", &miles))
return -1;
total_miles += miles;
days++;
}
printf("Total miles: %.2lf / %d Days = %.2lf Average miles per day.\n",
total_miles, days, (days > 0) ? total_miles / days : 0.0);
return 0;
}
Related
I need to figure out how to continuously add to the running total of avg mpg and divide by how many times it goes through.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg;
while (miles != -1) {
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg = mpg;
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", avg);
}
}
Okay so I think I got what you are trying to say, so first of all you should initialize avg = 0; and instead of changing avg = mpg; every time the loop runs you should do avg += mpg; so that it will add the previous values to next time the loop runs, Take another int to find the total average, initialize from 0 int t_avg = 0; and for next thing, dividing how many times it goes through you should take a variable and initialize it t = 0; and just increment t every time the loop runs so you will get the time loop goes on and you just have to divide it with avg.
And I would suggest you to use do while loop instead of while so that would be much better.
Hope this is what you were looking for.
#include <stdio.h>
int main() {
int miles;
int gallons;
int mpg;
int avg = 0, t = 0,t_avg = 0;
do {
t++;
printf("Enter number of miles driven(-1 to quit): ");
scanf("%d", &miles);
printf("Enter gallons used: ");
scanf("%d", &gallons);
mpg = miles / gallons;
avg += mpg;
t_avg = avg/t;
// adding average every time and diving every time the loop runs
printf("MPG this trip: %d\n", mpg);
printf("Avg MPG(so far): %d\n", t_avg);
}while(miles != -1);
}
I'm new at this and having some trouble. I'm trying to find the average of the grades that are inputed by the user but I realized that if you use a decimal in any of the grades, it's just being calculated as if they are whole numbers.
#include <stdio.h>
int main(void)
{
unsigned int counter;
float grade;
int total;
float average;
int number;
total = 0;
counter = 1;
printf("Number of scores to enter:\t");
scanf("%d", &number);
printf("\n");
while (counter <= number) {
printf("%s%d%s", "Enter the score for Lab ", counter, ":\t");
scanf("%f", &grade);
total = total + grade;
counter = counter + 1;
}
printf("\n");
average = (float) total / number;
printf("Average lab score: %.1f\n", average);
if (grade>=90) {
puts("Letter grade: A");
}
else if (grade>=80) {
puts("Letter grade: B");
}
else if (grade>=70) {
puts("Letter grade: C");
}
else if (grade>=60) {
puts("Letter grade: D");
}
else {
puts("Letter grade: F");
}
return 0;
}
You are capturing scanf("%f", &grade); as a float and then calculating total = total + grade;.
You have defined int total;. You would need to define it as float total;.
You are moving a float variable into an integer which is truncating the decimals you had previously entered.
There's no need to ask up front how many data points will be entered. Indeed, that is an anti-pattern. Just do something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
printf("Average lab score: %.1f\n", average);
fputs("Letter grade: ", stdout);
putchar( average >= 90.0 ? 'A' : average >= 80.0 ? 'B' :
average >= 70.0 ? 'C' : average >= 60.0 ? 'D' : 'F');
putchar('\n');
return average >= 60.0;
}
$ echo 78.2 96.5 80 | ./a.out
Average lab score: 84.9
Letter grade: B
Key points: total needs to be a float type. You must check the value returned by scanf. Always. Probably you want to handle bad input more cleanly that this does. This just throws away all data after an error and computes the average based on whatever data was entered prior to the error. A cleaner solution would abort with an error message. Exercise left for the reader.
A reasonable argument can be made that this is an abuse of the ternary operator; however you want to refactor it, don't repeat yourself by hardcoding the string "Letter grade: " multiple times.
Rather than abusing the ternary operator as above, you may prefer something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
int s = 'A' + (99 - (int)average) / 10;
printf("Average lab score: %.1f\n", average);
printf("Letter grade: %c\n", s > 'D' ? 'F' : s);
return average >= 60.0;
}
this code just generates a random number to be taken in as the temperature and records it every hour. I am having issues with my for loop on getting the max and min values of my code. It looks correct to me and similar to all the examples I have seen but it's giving me the wrong output.
Thank you
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main() {
int x, max, min, temperature[25];
float sum;
float average;
int array[array_size];
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < 25; x++) {
//if statements to get min and max
GetValue(temperature, x);
if (temperature[x] > max) {
max = temperature[x];
}
if (temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x,temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", temperature[12],max, min);
//adds up all temps
sum=0;
for (x=0;x<25;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/25;
printf("Average Temperature for the day: %.2f Degrees F\n",average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}
You invoked undefine behavior by using values of uninitialized variables having automatic storage duration, which is indeterminate.
Use values of variables only after assigning some value to them.
Format your code properly.
Match format specifier and data for printf().
Avoid using magic number. Use the #defined number for number of elements in this case.
Corrected code:
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main(void) {
int x, max = 0, min = 0, temperature[array_size];
float sum;
float average;
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < array_size; x++) {
//if statements to get min and max
GetValue(temperature, x);
// in the first iteration, there won't be a valid number in max and min
if (x == 0 || temperature[x] > max) {
max = temperature[x];
}
if (x == 0 || temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x, temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", max, min);
//adds up all temps
sum=0;
for (x=0;x<array_size;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/array_size;
printf("Average Temperature for the day: %.2f Degrees F\n", average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}
Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}
This program gets 5 numbers only from the user then
Store them in an array. Get the min, max, and the average of the numbers inputted. Here's the code I made:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int min, max=0;
int counter;
float average, total;
max = num[0];
min = num[2];
for(counter=0; counter<=4; counter++)
{
printf("Enter a number: ");
scanf("%d", &num[counter]);
if(num[counter]>max)
{
max = num[counter];
}
if (num[counter]<min)
{
min = num[counter];
}
}
total = max+min;
average = total/2;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average is: %d", average);
getch();
return 0;
}
FInally fixed my error with the min and max and now I'm having trouble with the average. I should only get the average of the min and max numbers but it keeps on showing an average of zero. Can someone help? Thankkyouuu.
//get memory address and store value in it.
void getValue(int *ptr)
{
printf("Enter a number: ");
scanf("%d", ptr);
}
int main()
{
//initialized n=5 as per your requirement. You can even get the value at run time.
int min, max, counter,n=5;
int num[n];
float average,total;
getValue(num); //get num[0]
min=max=total=num[0]; //Initialize min,max,total with num[0]
for(counter=1; counter<n; counter++)
{
getValue(num+counter); //get num[counter]
num[counter]>max?max = num[counter]:max; //find max
num[counter]<min?min = num[counter]:min; //find min
total+=num[counter]; // total = total + num[counter]
}
average = total/n;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The total is: %f\n", total);
printf("The average is: %f\n", average);
return 0;
}
Your calculation of average is wrong; you need to use total/num (remember use float):
total += num[counter];
max and min were incorrectly initialized: num[0], num[2] may be anything when you initialize them.
Aside from your calculation of average being wrong (it's not just total/2), you need to use the correct format specifier in the printf:
printf("The average is: %g", average);
You are using %d which tells printf to expect an integer, but you're giving it a float.
1 Min and max should be initialized
int min = INT_MAX;
int max = INT_MIN;
2 You need to keep a running total of your numbers
int total = 0;
...
// inside loop
scanf("%d", &num[counter]);
total += num[counter];
3 At the end print the average, recommend going to floating point.
printf("The average is: %.1f", (double)total/counter);