C Programming - Average - c

Okay I'm entirely stuck here and I do apologise if this inconviences you guys in any way but I need your help.
I'm currently learning C by myself and slowly getting there, started yesterday. So I thought I would give myself a task on having the user input 3 numbers and the program would have to find the average number between those three.
Here is my code:
#include <stdio.h>
int main() {
int firstnum, secnum, thirnum, finalnum;
printf("Enter the first number \n");
scanf("%f",&firstnum);
printf("Enter the second number \n");
scanf("%s",&secnum);
printf("Enter the third number \n");
scanf("%t",&thirnum);
finalnum = (firstnum +secnum+thirnum)/3;
printf("The average value is: " finalnum);
return finalnum;
}

Reading integers or floats: Correct format specifier
For integers you'll need %dand for doubles %lf. Read more about those elsewhere.
E.g.
scanf("%d",&firstnum);
Printing integers or floats
E.g.
printf("The average value is: %d", finalnum);
Avoid integer division: casting or all floats
See http://mathworld.wolfram.com/IntegerDivision.html
E.g.
double finalnum = (firstnum +secnum+thirnum)/3.0;
Or use floats for all types.
double firstnum, secnum, thirnum, finalnum;
Return 0 for success in main
return 0;

I found the fix linking with the comments made by harre and Klas Lindbäck. Thank you both.
I changed my format specifiers to %d as suggested. I then changed my printf line a little bit more.
I then tried to make a float with my int > finalnum but it didn't work. All this did was continously return the average as '0' so I placed finalnum back as an int. This is how the code looks now:
#include <stdio.h>
int main() {
int firstnum, secnum, thirnum;
int finalnum;
printf("Enter the first number \n");
scanf("%d",&firstnum);
printf("Enter the second number \n");
scanf("%d",&secnum);
printf("Enter the third number \n");
scanf("%d",&thirnum);
finalnum = (firstnum + secnum + thirnum)/3;
printf("The average value is: %d", finalnum);
return finalnum;
}
Thank you all :)

Use float instead of int to get decimal precision
otherwise the finalnum would get rounded off
use this for printing float
printf("The average value is: %f",finalnum);
for more on printf you can refer this link
http://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

Related

i am getting a unknown error in my c program

Code:
#include <stdio.h>
void main()
{
int s1,s2,s3,s4,s5,sum;
float per;
printf("Enter subject 1 marks out of 100 \n");
scanf("%d",s1);
printf("Enter subject 2 marks out of 100\n");
scanf("%d",s2);
printf("Enter subject 3 marks out of 100 \n");
scanf("%d",s3);
printf("Enter subject 4 marks out of 100\n");
scanf("%d",s4);
printf("Enter subject 5 marks out of 100\n");
scanf("%d",s5);
sum=s1+s2+s3+s4+s5;
per=sum/100;
if (per>60 && per<70){
printf("your percentage is %d and you get 10% schoolarship",per)
;}
else if (per>70.1 && per<90){
printf("your percentage is %d and you get 20% schoolarship",per)
;}
else {
printf("your percentage is %d and you get 30% schoolarship",per)
;}
}
Output:
I am trying to make a percentage calculator and it shows a weird output.
What am I doing wrong?
When you call scanf, it is important to pass in the address of the variable you want to store. Otherwise, scanf will not behave as you expect.
Right now, you are not passing in the address to scanf; but rather the variable itself.
So you should do something like:
scanf("%d",&s1);
instead.
https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
I recommend reading a little bit about how scanf works at the following link.
"Following is the declaration for scanf() function.
int scanf(const char *format, ...)"
Additionally, check out this link for a few examples of scanf:
https://www.programiz.com/c-programming/c-input-output
scanf("%d", &testInteger);
The syntax is format first, then pass in the address of where you want to store the data.
scanf() requires a pointer to the value, it should be scanf("%d",&s1);

My factorial and power functions output a number in the millions when it shouldn't and I don't know how to fix it(in c)

I am trying to write a sort of calculator program and i can get everything but my factorial and power functions to work. They output a number in the millions no matter how small the number is and i don't see a problem with the code. (I just started learning C recently so assume the extent of my knowledge is everything in this code)
int iFactorial(num1){//needs help returns a number in the millions no matter what
int i, factorial=1;
printf("Enter a positive number: ");
scanf("%d", &num1);
for(i=1; i<=num1; i++)
factorial*=i;
printf("The factorial is %i", &factorial);
return 0;
}
int fPower(num1,num2){//needs help, same as above
int i, number = 1;
printf("Enter the number you want to raise to a power: \n");
scanf("%d", &num1);
printf("Enter the exponent: ");
scanf("%d", &num2);
for(i=0; i<num2; i++)
number*=num1;
printf("%d to the %d equals %d", &num1, &num2, &number);
return 0;
}
You are using & in the print statement that prints the address of the variable used.
Correct the statements in their respective function as follows :
printf("The factorial is %i", factorial);
printf("%d to the %d equals %d", num1, num2, number);
Your printf for the factorial and power cases are mal-formed, you are passing the arguments by pointer; you need to pass them by value.
After that, you'll realise quickly that you'll overflow the int type in the factorial and power cases. An int in general is only good up to and including 7! in truly portable C++. Consider using an unsigned long long, which will give you values up to and including 21!. Use "%ull" for an unsigned long long in the formatter.
Finally, pass the types explicitly to your functions in C: your style has been explicitly disallowed since C99.
You're using the wrong format specifiers to printf to print the results, and you're not passing the actual values you want to print:
printf("The factorial is %i", &factorial);
You're passing in the address of factorial instead of its value, so it's printing that instead. Just pass the result directly instead of its address:
printf("The factorial is %i", factorial);

Find the sum of two numbers which are in the separate line?

So there is a problem on SPOJ as mentioned below:
Given two natural numbers (both not greater than 200), each number in the separate line, please print the sum of them.
Example Input:
2
3
Output: 5
So I wrote a program to this problem. Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int input1, input2, sum;
printf("Enter two natural numbers\n");
scanf("%d", &input1);
scanf("\n%d", &input2);
if ((input1>0&&input1<=200) && (input2>0&&input2<=200))
{
sum = input1 + input2;
printf("%d", sum);
}
return 0;
}
But SPOJ rejected this answer as a wrong answer.
Later I checked this on idone.
But I'm unable to detect, what's wrong with this answer, as expected it gives the same output given in above question.
Please correct if I'm wrong.
The first print statement
printf("enter two natural numbers\n");
The Second
scanf("%d",&input1);//Press Enter
The Third
scanf("%d",&input2);//Press Enter
And finally
printf("\n%d",sum);
First of all, remove the printf statement as it is not needed and will mess up the expected I/O as given by SPOJ.
Next, there is no need of the newline character in scanf. You can directly write scanf("%d %d", &input1, &input2);. Another way would be to write the scanf statement twice as:
scanf("%d", &input1);
scanf("%d", &input2);
Lastly, you can also remove the if statement, if input bounds are given by SPOJ.

Converting a Character String to a Float

I'm trying to take the user input, which is a character string, and convert it to a float. In my case, gas keeps being printed as 55.000000 when the user enters 7 - I'd like it to be printed as 7.0.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main()
{
char gas_gallons;
float gas;
printf("Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
while (!isdigit(gas_gallons))
{
printf("\nYou need to enter a digit. Please enter the number of gallons of gasoline: ");
scanf("%c", &gas_gallons);
}
if (isdigit(gas_gallons))
{
printf("\nHello %c", gas_gallons);
gas = gas_gallons;
printf("\nHello f", gas);
}
return 0;
}
Why not do this? It's much simpler.
#include<stdio.h>
int main()
{
int gas;
printf("Please enter the number of gallons of gasoline.\n : ");
//use the %d specifier to get an integer. This is more direct.
//It will also allow the user to order more than 9 gallons of gas.
scanf("%d", &gas);
printf("\nHello %d", gas);//prints integer value of gas
//Using the .1f allows you to get one place beyond the decimal
//so you get the .0 after the integer entered.
printf("\nHello %.1f\n", (float) gas);//print floating point
return 0;
}
You said:
In my case, gas keeps being printed as 55.000000 when the user enters 7
When the user enters 7 as input the digit 7 is stored as the character in gas_gallons. The decimal value of the character 7 is 55 in ASCII encoding. You can see the decimal values of other characters in ASCII encoding at Wikipedia and many other places on the web.
When you use:
gas = gas_gallons;
the integer value of gas_gallons is, i.e. 55, is assigned to gas. That explains why you get 55.000000 as the output when you print gas.
You can fix the problem many ways. Here are a couple of suggestions.
Option 1
Convert the digit to a number by using:
gas = gas_gallons - '0';
Option 2
Discard the code to read the number of gallons of gasoline as a digit and converting the digit to a number. Using a digit is also limiting since you cannot have 10 or 12.5 as input.
Read the number of gallons of gasoline as a number directly. With this approach, your input can be a any floating point number that can be represented by a float.
#include <stdio.h>
int main()
{
float num_gallons;
while ( 1 )
{
printf("Please enter the number of gallons of gasoline: ");
// Read the number of gallons of gas.
// If reading is successful, break of the loop.
if (scanf("%f", &num_gallons) == 1 )
{
break;
}
// There was an error.
// Read and discard the rest of the line in the input
// stream.
scanf("%*[^\n]%*c");
printf("There was an error in reading the gallons of gasoline.\n");
}
printf("\nHello %f\n", num_gallons);
return 0;
}
The ASCII-characters '0'-'9' do not have the integer values 0-9. You can find the appropriate value by subtracting '0'.
To convert a string to float you can use atof (ASCII to float) function included in stdlib.h.
Here is the full declaration of this function: double atof(const char *str)
so you can do a simple cast
gas = (float) atof(gas_gallons);

Why is my C program printing 0.000000 here?

I just started to learn C programming.
In my book there is this piece of code:
/*Code Start*/
/*This code is use to find the simple interest*/
main ()
{
int p, n;
float r, si;
p = 1000;
n = 3;
r = 8.5;
si= p*n*r/100;
printf("%f", si);
}
/*Code end*/
The output i got was " 255.000000 "
I though i'll modify it with scanf function so i wrote this:
/*Code Start*/
main ()
{
int p, n;
float r, si;
printf("Enter value for p: \n");
scanf("%d", &p);
printf("Enter value for n: \n\n");
scanf("%d", &n);
printf("Enter valuse for r: \n\n");
scanf("%d", &r);
si= p*n*r/100;
printf("\nYour Simple Interest is %f\n\n", si);
}
/*Code End*/
No matter what values i give to p,n,r the answer i get is always 0.000000..
I also tried giving the values, p=1000, n=3, r=8.5 but still i get 0.000000..
Change the specifier in scanf. You're using %d instead of %f:
scanf("%f", &r);
^
First side note: the code looks kind of bad (no return type for main ?!). Are you sure it's a good book ?
Second side note: using floats today is kind of pointless. Maybe you
should use doubles ?
Firstly, your main problem: The %d specifier is only for integers, not floats or doubles. Use %f for floats.
In addition, the main should return an int, this will do:
int main() {
/* your code */
return 0;
}
Finally, I would recommend you make better use of white-space as it will vastly help with readability once you start making larger programs.
Use %f conversion specification to read a float:
scanf("%f", &r);
%d means it reads a decimal integer and not a float.
r is a float, but you're reading it in using %d as a scanf specifier, which expects an int.
The real culprit in your code is the line scanf("**%d**", &r).
%d is the format specifier for integer value, as you declared r as float then use %f instead of %d.
i.e. scanf("%f", &r)
Change Either
int p, n;
float r, si;
to
int p, n,r;
float si;
or change formate specifier in scanf("%d", &r); %d to %f.
when you declare r as an integer r=8 will be considered, in that case scanf("%d", &r); will be accepted. and your program get compiled and executed.
both declaration and formate specifier should be same.
my suggestion is to use %.2f when dealing with money. which will give like 10.00 which is the correct formate.

Resources