I am very new to C and to programming and I am having issues with getting the average of 5 numbers. I have tried everything I could think of and I have not clue why I am not getting a number besides 0. My code is:
#include <stdio.h>
int main (void)
{
long int first,second,third,fourth,fifth, sum;
float avg = (first+second+third+fourth+fifth)/5;
printf("Please put in five numbers\n");
scanf("%d%d%d%d%d", &first, &second, &third, &fourth, &fifth);
printf("You entered: %d %d %d %d %d\n" , first, second, third, fourth, fifth);
sum = first+second+third+fourth+fifth;
printf("The sum of the numbers you entered is %d\n",
sum);
printf("The average is %d\n", avg);
return 0;
}
I think the problem is that you are initialising average value with the variables that are given after calculating average .Try to calculate average value after giving the variables i.e first,second,third,fourth and fifth.
The main problem is that you calculate the average before getting the numbers. The values of the uninitialized variables happened to be 0, and the average of five zeros is a zero, too.
The second problem is that you divide a sum of integer numbers by another integer number. Integer division discards the fractional part of the quotient.
The line:
float avg = (first+second+third+fourth+fifth)/5;
must be moved after scanf, and 5 must become 5.0. The result should be displayed as a floating-point number with %f, not with %d.
There are four problems in your code :
You are calculating average before you take in variable.
You are dividing a sum of integer with other integer due to which , the fractional part will truncate.Integer division truncates the fractional part.
You are printing avg which you defined as float with format specifier %d so it will cause undefined behaviour.
You are using %d specifier for long int , it should %ld.
Taking Into Account All These Problem Your Code Becomes.
#include <stdio.h>
int main (void){
long int first,second,third,fourth,fifth, sum;
printf("Please put in five numbers\n");
scanf("%ld%ld%ld%ld%ld", &first, &second, &third, &fourth, &fifth);
//Changed Due To Problem 4.
printf("You entered: %ld %ld %ld %ld %ld\n" , first, second, third, fourth, fifth);
sum = first+second+third+fourth+fifth;
float avg = (sum)/5.0; //Changed Problem No.2 and N0.1
printf("The sum of the numbers you entered is %ld\n", //Changed Due To Problem 4.
sum);
printf("The average is %f\n", avg); //Changed Problem No.3
return 0;
}
Tip
Always Try To solve the problem yourself before asking for help , it will benefit you more.
And First Have It Ready On a Paper Before Coding , it will decrease many bugs.
Related
I want to be able to take someones amount owed as the price, and then do some math from the amount received and print my result.
Below is the code I came up with. However, my program does not run after showing the amount tendered.
Any thoughts?
Note, it is my first time coding in C, and I'm from Java..
#include <stdio.h>
int main (void) {
double tendered;
double changeDue;
double price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
int toonoe=0;
int loonie=0;
int quarter=0;
int dime=0;
int nickle=0;
int penny=0;
/* Statements to be executed */
printf("Total purchase price and tendered amount");
scanf("%lf%lf", &price, &tendered);
printf("The sum of %lf and %lf is ", tendered,price);
changeDue=tendered-price;
while(changeDue!=0.00){
if(changeDue<=100.00){
changeDue=changeDue-100.00;
hundred=hundred+1;
}
if(changeDue<=20.00){
changeDue=changeDue-20.00;
twenty=twenty+1;
}
if(changeDue<=10){
changeDue=changeDue-10.00;
ten=ten+1;
}
if(changeDue<=5){
changeDue=changeDue-5.00;
five=five+1;
}
if(changeDue<=2){
changeDue=changeDue-2.00;
toonoe=toonoe+1;
}
if(changeDue<=1){
changeDue=changeDue-1.00;
loonie=loonie+1;
}
if(changeDue>1){
for(int i=0;i<changeDue;i++){
if(i==0.25&&changeDue>=0.25){
changeDue=changeDue-0.25;
quarter=quarter+1;
}
if(i==0.10&&changeDue>=0.10){
changeDue=changeDue-0.10;
dime=dime+1;
}
if(i==0.05&&changeDue>=0.05){
changeDue=changeDue-0.05;
nickle=nickle+1;
}
if(i==0.01&&changeDue<0.05){
changeDue=changeDue-0.01;
penny=penny+1;
}
}
}
}
if(hundred!=0){
printf("%d hundred$ bills given as change",hundred);
}
if(twenty!=0){
printf("%d twenty$ bills given as change",twenty);
}
if(ten!=0){
printf("%d ten$ bills given as change",ten);
}
if(five!=0){
printf("%d five$ bills given as change",five);
}
if(toonoe!=0){
printf("%d toonie coins given as change",toonoe);
}
if(loonie!=0){
printf("%d loonie coins given as change",loonie);
}
if(quarter!=0){
printf("%d quarter coins given as change",quarter);
}
if(dime!=0){
printf("%d dime coins given as change",dime);
}
if(nickle!=0){
printf("%d nicke coins given as change",nickle);
}
if(penny!=0){
printf("%d penny coins given as change",penny);
}
return 0;
}
I have an alternative version of that code, which changes the first part of scanning and printing to
/* identical to start of first version ... */
/* Statements to be executed */
printf("Total purchase price");
scanf("%d", &price);
printf("Enter amount recieved by customer ");
scanf("%d", &tendered);
printf("%d", &tendered);
printf("%d",&tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
And I have a third version, where first scanning and printing is like this.
/* identical to start of first version ... */
float tendered;
float changeDue;
float price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
float toonoe=0;
float loonie=0;
float quarter=0;
float dime=0;
float nickle=0;
float penny=0;
/* Statements to be executed */
printf("Total purchase price");
scanf("%f", &price);
printf("Enter amount recieved by customer ");
scanf("%f", &tendered);
printf("%f tendered", tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
You have the problem of comparing a floating point value for identity
(or for not being identical, same problem) here:
while(changeDue!=0.00){
See here for some background:
Is floating point math broken?
It creates an endless loop (at least if you are not "lucky"), which prevents all further printing. (Actually "lucky" is not a good description for hiding a bug...)
In order to verify this diagnose, insert a printf at the start of the loop.
while(changeDue!=0.00){
printf("Making change...\n");
You will see many more of that debug output line than you expect.
In order to solve that endless-loop problem, change to
while(changeDue>=0.01)
and the endless loop is solved, which currently prevents anything visible happen after printing the due amount.
This does not necessarily fix all the problems in your code, but the most prominent one described in your question is solved.
Note that one of the comments recommends to use int for currency.
I normally agree, but I have accepted your statement that you have to use float/double.
By the way, use the first version of the code.
In the second version you are printing the address of something instead of the value. I.e. the & is wrong here:
printf("%d", &tendered);
In the third version your types and the format string in printf do not match.
I am asked to come up with a code register which its input is followed by:
Please enter the amount to be paid: $8.68
Loonies required: 8, balance owing $0.68
Quarters required: 2, balance owing $0.18
The first sentence is completed, but the second isn't, as the comma before the address overlaps with the comma before the word 'balance.'
Is there any way to display comma just as above, and maintain the comma for the address?
#include <stdio.h>
int main(void){
int n_loonies;
int n_quarters;
float remaining;
double amount;
amount = 8.68;
n_loonies = amount / 1;
remaining_loonies = amount -(n_loonies * 1);
n_quarters = amount / 0.25;
remaining_quarters = amount - (n_quarters * 25);
printf("Please enter the amount to be paid:$");
scanf("%lf", &amount);
// printf("loonies required: n_loonies");
// scanf("%d", &n_loonies);
printf("Loonies required:%d,n_loonies, balance owing $%d\n);
return 0;
}
Looks like your print statement is a bit off. It doesn't look like that code would compile, here is an example of how to use print:
int x = 10;
printf("x: %d, x address: %p\n", x, (int *)&x);
There are a number of problems with your code
1) Undeclared variables, e.g. remaining_loonies
2) The scanf is placed after all the calculations so the user input is just ignored
3) The printf is called incorrectly
printf needs a format string and after the format string comes the variables you want to print. All separated by commas.
In the format string the variables are given as % followed by a letter that tells the type of the variable to print, e.g. %d for a signed integer variable, %u for an unsigned integer variable, %f for a float variable and some more...
So to print a single integer do
int my_quaters = 5;
format string
|------------------|
printf("I got %d quaters\n", my_quaters);
^^ ^^
Integer type The variable
When the printf is executed %d will be replaced by the current value of the variable my_quaters - so this will print:
I got 5 quaters
To print two integers do
int my_quaters = 5;
int my_pence = 15;
printf("I got %d quaters and %d pence \n", my_quaters, my_pence);
^^ ^^ ^^ ^^
Integer type Integer type First var Second var
this will print:
I got 5 quaters and 15 pence
So in your case it is more like:
printf("\nLoonies required:%d, balance owing $%.2f\n", n_loonies, remaining_loonies);
note: The format string has a lot more options than I can mention here. Read a good book or man page for that.
#include <stdio.h>
#include <stdlib.h>
int main()
{
{
float test1Marks, test2Marks, test3Marks, averageMarks;
averageMarks = (test1Marks + test2Marks + test3Marks) / 3;
printf("Test 1 Marks:");
scanf("%f", &test1Marks);
printf("Test 2 Marks:");
scanf("%f", &test2Marks);
printf("Test 3 Marks:");
scanf("%f", &test3Marks);
printf("Average Marks of tests are:%f", averageMarks);
}
return 0;
}
Everything alright but the final output which gives average is wrong.
But when I assign values to two of the variables and input third ones value by scanf syntax then it gives the average otherwise not.
Move averageMarks=(test1Marks+test2Marks+test3Marks)/3; after the last scanf but before the print statement in which you are printing the average!
int main()
{
float test1Marks,test2Marks,test3Marks,averageMarks;
printf("Test 1 Marks:");
scanf("%f",&test1Marks);
printf("Test 2 Marks:");
scanf("%f",&test2Marks);
printf("Test 3 Marks:");
scanf("%f",&test3Marks);
/* Now with determined test1Marks, test2Marks, and test3Marks
values we can compute their average:
*/
averageMarks=(test1Marks+test2Marks+test3Marks)/3;
printf("Average Marks of tests are:%f",averageMarks);
return 0;
}
You need to read values into your variables before computing the average #John Bode 1
Compute averageMarks=(test1Marks+test2Marks+test3Marks)/3; after the values are read.
In another language this approach may work, yet C requires sequential evaluation.
averageMarks=(test1Marks+test2Marks+test3Marks)/3; is not a function, it is a series of statements to do something, where it adds the values in those variable at the time it is run, and then divides by 3, and assigns the result to averageMarks.
when you read in the values, scanf puts whatever value it reads into the variables when it is executed, and then you print out the averageMarks, which was already computed and stored earlier with the empty variables you made with the first statement.
My program to check Armstrong Number of 'n' digits is giving a wrong output, only when the input is 153.
Here is my code.
#include<stdio.h>
#include<math.h>
int main()
{
int p, k, n, t, sum, n1, m;
printf("Enter the number: ");
scanf("%d", &n);
n1=n;
for(p=0, k=1; n/k>=1; ++p, k*=10);
printf("\nThe number of digits: %d", p);
for(sum=0; n>0; n/=10)
{
t= n%10;
printf("\n\nThe base and power: %d and %d", t, p);
m=pow(t, p);
printf("\nThe calculated no is: %d", m);
sum+=pow(t, p);
printf("\nThe sum is: %d", sum);
}
printf("\n\t The original number is : %d", n1);
printf("\n\t The calculated number is: %d", sum);
if(n1==sum)
printf("\n\t%d is an armstrong number\n", n1);
else
printf("\n\t%d is not an armstrong number\n", n1);
return 0;
}
The program is getting 152 when it does the math and is therefore giving a wrong output. I have printed every step to find the exact point of error.
I have used power function instead of for loops
I cannot use t* t*t as this program is for Armstrong numbers of "n" digits, and not only 3
I am compiling the program using Code Blocks 16.01
The problem is, it is calculating the cube of 5 as 124.
Interestingly I am getting the correct answer(125) when I use the power function to calculate the cube of 5 in a separate, simple program.
I also checked the code given here -->https://www.programiz.com/c-programming/examples/check-armstrong-number which is also giving the wrong output. The answers to the somewhat similar questions that I found on this website didn't solve the problem.
Well, I'm not able to reproduce the said problem. I do get the correct result for input 153, i.e. that it is an Armstrong number.
It could be some floating point rounding error due to use of pow (though I would find that strange in this specific case).
For a task like this one, you should not use floating point. Use the largest integer type available. Not only do you avoid nasty rounding errors but you also increases the range of input values that your program can handle.
So, I like to address this part:
I cannot use t* t*t as this program is for Armstrong numbers of "n" digits, and not only 3
You can easily write a function that calculates t^n using integer math. Here is an example:
#include<inttypes.h>
uint64_t intpow(uint64_t t, uint64_t p)
{
uint64_t result = 1;
while(p>0)
{
result = result * t;
--p;
}
return result;
}
Notice: In its current form the function lacks overflow detection as I wanted to keep the function simple.
There are Two ways to solve.
1) Use round() function which will give the nearest integer (because there is some error in floating point calculation in codeblocks).
2) Declare your sum variable as float or double because then it will convert into perfect floating point precision.
I'm in a programming class right now, and was asked to create a program that calculated the sum of a user's input for multiple numbers--then calculate the nth root of the sum. If the number they input was less than 0, the loop is supposed to discard the less than 0 number, then ask again.
Unfortunately, no matter what number I input--it displays "Value needs to be greater than zero!" I tried putting a fflush(stdin); statement in the loop, but that didn't seem to do anything.
Here is my code. I really appreciate any and all help.
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
int mTotalNums, mNth; //amount of numbers in set
float mProd = 1, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
mNth = mTotalNums; //set the value of mTotalNums equal to mNth becuase we'll lose the original value of mTotalNums after the loop
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
}
mNroot = pow(mProd, (1 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
"%lf" is the scanf format for a double, but x is declared as float.
To scan a float, you have to use the %f format.
Note also that mTotalNums is not decremented in the loop, so that it will never
terminate.
Read the documentation of scanf(3). Since x is declared as a float, use %f as the scanf format control string. Also, take into account the result of scanf (it would be 1 if successfully read one item).
You should enable all warnings and debug info in your compiler, then learn how to use the debugger (notably to run your program step by step, display local variables, etc....).
(On Linux, if compiling with gcc -Wall -g you would get a useful warning, and the gdb debugger would be helpful...)
Try these modifications to your program (added comments with changes made)
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
//amount of numbers in set
int mTotalNums, mNth;
// Change to double for added precision
double mProd = 1.0, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
// Set the value of mTotalNums equal to mNth becuase
// we'll lose the original value of mTotalNums after the loop
mNth = mTotalNums;
// Don't forget to decrement the loop counter
while (mTotalNums-- > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else {
printf("\nValue needs to be greater than zero!\n");
}
}
// Change to 1.0 to force compiler to treat as a double
mNroot = pow(mProd, (1.0 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
You mention "calculate the nth root of the sum", but your loop is clearly tallying the cumulative product. To change it to calculate the sum, try the following additions:
// Declare a sum variable
double sum = 0;
// Sum inside your while loop
sum += x;
// Calculate the nth root of the sum instead
mNroot = pow(sum, (1.0 / mNth));
Add printf commands to see what your variables contain before you check them in your logic statements.
You also need to do something to increment/decrement your variable for your while loop... currently nothing is changing mTotalNums, so it will be an infinite loop.
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
printf("x=%d", x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
mTotalNums--;
}