Not able to calculate in C.How do you calculate in C? - c

Im new to C and I really don't know know what I'm doing wrong.
The issue that I am having is I'm supposed to ask 3 questions of the user using scanf. I'm supposed to ask the user for an integer, a positive real number and a non negative number and then calculate the numbers into XX.XX using %.2f.
//pre-processor directives
#include <stdio.h>
#include <math.h>
//main function
int main()
{
//declare variables
int smp1,smp2, smp3,total;
printf("sample 1?\n"); // positive integer
scanf("%d", &smp1);
printf("sample 2?\n"); //positive real number
scanf("%f",&smp2);
printf("sample 3?\n"); // non negative number
scanf("%u", &smp3);
total = (smp1 + smp2 / smp3);
printf("The final result is %.2f",total);
//end of main
return 0;
}
No matter what I put in there my result ends up being 0.00. It won't even do simple addition and I don't know enough to know why.

Your main issue is that you declare all your variables as ints, but smp2 and total must hold floating point values.
Change your declarations to
int smp1;
double smp2, total;
unsigned int smp3;
This way, the types of the variables match up with the conversion specifiers used in the printf and scanf calls.
Types matter in C, and it's up to you that the types of the arguments in each printf and scanf call match up with the conversion specifiers.
Check your compiler documentation on how to enable warnings (even better, to treat all warnings as errors). Most compilers should warn about type mismatches like this, but sometimes you have to set a flag in order for those warnings to appear.

Related

Why my answer is 0.00.. confuse how to convert int to float struct

there's something wrong in these variables.
can someone fix this? my answer keep getting on 0.00
Test case:
we want to find the mean between 3 numbers using struct
input=2,
2 of them are: 3 5 8 and 3 5 7
out put should be:
//*3+5+8=(16)/3=5.33
//*3+5+7=(15)/3=5.00
#include<stdio.h>
struct rata{
float in1;
float in2;
float in3;
};
float rata2(in1,in2,in3){
return (float)((in1+in2+in3)/3);
}
void main(){
int i,n;
char hasil[100];
scanf("%d",&n);
struct rata walao;
for (i=0;i<n;i++){
scanf("%d %d %d",&walao.in1,&walao.in2,&walao.in3);
hasil[i]=rata2(walao.in1,walao.in2,walao.in3);
}
for (i=0;i<n;i++){
printf("%.2f\n",hasil[i]);
}
}
There are 3 errors in your code that is preventing you from getting the correct answer. Can you find them? Here's a hint, they have to do with types.
Below are the answers and the reasons behind them.
char hasil[100] is assigning hasil to be a char array of size 100. While chars can be assigned numerical values, they are to be treated as integers if they are. Floats =/= Integers, and this should be rectified by saying float hasil[100]
scanf("%d %d %d",&walao.in1,&walao.in2,&walao.in3) is scanning for 3 digits. Since floats can also be assigned integer values, this is valid. However, the language requires that all values used in a calculation should be the same type (hint for 3!). To fix you can do 1 of 2 things, both are legal but entirely up to you. You can either write it as scanf("%f %f %f",&walao.in1,&walao.in2,&walao.in3) or keep it as is. Your choice will come to play in final error
The input rata2 is taking is unspecified. Is it ints? floats? chars? It doesn't know but it trys to resort to using ints, as mostly everything in C can be represented by a number. Since it resorts to ints, the value returned by your calculation is an int as well and no late cast to float will change that. Those variables need to be specified as something and how you handled error 2 decides what you do here. If you changed the earlier scanf to take floats instead of digits, rewrite rata as float rata2(float in1, float in2, float in3), remove the cast and you're done. If you kept as is, rewrite rata as float rata2(int in1, int in2, int in3), and rewrite the return as return ((float)in1 + (float)in2 + (float)in3)/3;. Either course of action is acceptable but its far more easier and faster specifying them as floats then trying to cast everything (Plus its a LOT cleaner).
This should rectify your code (tested it on my machine). Also, for future note, do
scanf("%d",&n);float hasil[n];
It makes more sense and you don't have to run into the issue of people specifying memory you don't have access to.

C : My 'Poisson calculator' gives me #1.INF00. Why does this happen?

Before anything, here's my code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
float Exp, Act, Px, Facto_Act;
printf("\n This is Poisson Distribution Calculator!");
printf("\n Enter the expected value of success in a time period:");
scanf("%f",& Exp);
printf("\n Enter the actual or calculated value of success in a time period:");
scanf("%f",& Act);
Px=pow(M_E,-Exp)*pow(Exp,Act)/Facto_Act;
printf("\n Poisson probability is:%f", Px);
getch();
return 0;
}
Facto_Act(float Act)
{
float c;
float result=1;
for(c=1;c<=Act;c++)
result=result*c;
return result;
}
Further explanation:
Poisson equation looks like this:
P(x)= (e^-Lambda)(Lambda^x)/(x!)
Exp: Expected number of events in a given time(Lambda)
Act: Actual number of events in a given time(x)
Px: Probability of an event occuring in a given time( P(x) )
Facto_Act: Factorial of Actual number of events in a given time(x!)
When I figured out how to do factorials for integer in C, I will try to add factorials for positive decimals too. But #1.INF00 is not a value I expect.
When I compile the code, there are no more coding errors shown. But when I enter the expected value of successes in a period, then the actual value of succesess in a period, I always end up with #1.INF00. I am very noobful of C, and while this site has helped me improved my programs by a bit, I can't understand the '#1.INF00' means.
I decided not to make Facto_Act a function
I decided to circumvent the entire Facto_Act function problem by not making Facto_Act a function, then trying to call it. It seems that factorials can be performed without making a new function for it. Thus Facto_Act is now a variable. This is my new code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
double Exp, Px;
int c, Act, Act2, Facto_Act=1;
printf("\n This is Poisson Distribution Calculator!");
printf("\n Enter the expected value of success in a time period:");
scanf("%lf",& Exp);
printf("\n Enter the actual or calculated value of success
\n in a time period(must be an integer!):");
scanf("%d",& Act);
/*My factorial starts here*/
for (c=1;c<=Act;c++)
Facto_Act=Facto_Act*c;
/*My factorial ends here*/
Px=(pow(M_E,-Exp))*(pow(Exp,Act))/Facto_Act;
printf("\n Poisson probability is:%lf", Px);
getch();
return 0;
}
I thank you all for helping me out.
You declared a variable named FactoAct of type float. Since it is an extern variable with no initialisation, it has a value of 0.
Later you define a function Facto_Act(float Act) with an implicit return type of "int".
Your division xxx / FactoAct divides xxx by the variable FactoAct, which is zero. That's where your INF result comes from.
When you had the function at the top, when the compiler saw xxx / FactoAct, FactoAct was not the result of a call to the function, it was the function itself. You can't divide a number by a function. It doesn't make sense. The only thing you can do with a function is take its address, or call it.
You probably want FactoAct (x) or something like that.
PS. Don't use float instead of double, unless you have a reason that you can put into clear words why in your specific case float is better than double.

To generate an integer output for a float variable in c

Okay this is actually a very simple code but since I am only starting to learn C, please be patient and help me out. I'll be putting my Questions as comments beside the code so that it easy to relate to which part of the code I have a doubt.
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",output_no);
/*here I wanted to print only the integer part of the output_no */
}
The problem with this is that I had a book and it displayed the value for third no as 0.
And then in another program it says that compile time error is shown.
Second program:
#include <stdio.h>
void main()
{
int x = 5.3%2;
printf("Value of x is %d", x);
}
For this program, the book says that a compile time error will be shown. I fail to understand why that is the case. According to me the output should be 1.
If I were to use the following code instead of the previous code:
#include <stdio.h>
main()
{
int first_no, second_no;
float dec_no, output_no;
first_no = 75;
second_no = first_no/2;
dec_no = 35.3;
output_no = dec_no/3;
printf("First No:%d\n", first_no);
printf("Second No:%d\n", second_no);
printf("Third No:%d\n",dec_no);
}
What output should I expect? Do I still get a zero or some unpredictable output?
The problems with using just
printf("Third No:%d\n",output_no);
is that:
output_no gets converted to a double before being passed to printf.
When printf sees %d as the format specifier, it expects an int. When the object being passed is of type double, the behavior is undefined.
When you want to print a truncated integral value of a floating point number, you can do one of the following.
Create a temporary variable of the integral type and assign to it the floating point number.
int temp = output_no;
printf("Third No:%d\n", temp);
Explicitly cast the floating point number to an integral type.
printf("Third No:%d\n", (int)output_no);
printf("Third No:%d\n",dec_no);
What output should I expect? Do I
still get a zero or some unpredictable output?
As of the printf function is concerned,
When you try to print an integer value with format specifiers that are used for float (or) double and vice the versa the behaviour is unpredictable.
But it is possible to use %c to print the character equivalent of the integer value. Also using of %d to print ASCII value (integer representations) of character is acceptable.
Second program: For this program, the book says that a compile time
error will be shown.
According to C Reference manual
7.3.3 expression % expression
The binary % operator yields the remainder from the division of the first expression by the second. Both operands must be int or char, and
the result is int. In the current implementation, the remainder has
the same sign as the dividend.
Here in your case you are providing one value 5.3 so it is neither char nor int so that is why it generates compilation error.
If you still want to run that program you can do that by using fmod() function.
Try this code :
#include<stdio.h>
#include<math.h>
void main()
{
float x=5.3;
int c =2;
printf("Value of xremainer is %lf",fmod(x,c));
}
Compile it as :
$gcc test.c -lm

Why is prime number check getting wrong results for large numbers?

This small C script checks if a number is a prime... Unfortunately it doesn't fully work. I am aware of the inefficiency of the script (e.g. sqrt optimization), these are not the problem.
#include <stdio.h>
int main() {
int n, m;
printf("Enter an integer, that will be checked:\n"); // Set 'n' from commandline
scanf("%d", &n); // Set 'n' from commandline
//n = 5; // To specify 'n' inside code.
for (m = n-1; m >= 1; m--) {
if (m == 1) {
printf("The entered integer IS a prime.\n");
break;
}
if (n % m == 0) {
printf("The entered integer IS NOT a prime.\n");
break;
}
}
return 0;
}
I tested the programm with a lot of numbers and it worked... Then I tried a bigger number (1231231231231236) which is clearly not a prime...
BUT: the program told me it was!?
What am I missing...?
The number "1231231231231236" is too big to fit in an "int" data type. Add a printf statement to show what number your program thinks you gave it, and if that's prime, your program works fine; else, you might have a problem that merits checking. Adding support for integers of arbitary size requires considerable extra effort.
The reason you are having this problem is that intrinsic data types like int have a fixed size - probably 32 bits, or 4 bytes, for int. Given that, variables of type int can only represent 2^32 unique values - about 4 billion. Even if you were using unsigned int (you're not), the int type couldn't be used to store numbers bigger than around 4 billion. Your number is several orders of magnitude larger than that and, as such, when you try to put your input into the int variable, something happens, but I can tell you what doesn't happen: it doesn't get assigned the value 1231231231231236.
Hard to know without more details, but if your ints are 32-bit, then the value you've passed is outside the allowable range, which will no doubt be represented as something other than the value you've passed. You may want to consider using unsigned int instead.
The given number is too large for integer in C. Probably it only accepted a part of it. Try Printing the value of n.

How to printf long long

I'm doing a program that aproximate PI and i'm trying to use long long, but it isn't working.
Here is the code
#include<stdio.h>
#include<math.h>
typedef long long num;
main(){
num pi;
pi=0;
num e, n;
scanf("%d", &n);
for(e=0; 1;e++){
pi += ((pow((-1.0),e))/(2.0*e+1.0));
if(e%n==0)
printf("%15lld -> %1.16lld\n",e, 4*pi);
//printf("%lld\n",4*pi);
}
}
%lld is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d
So try this:
if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);
and
scanf("%I64d", &n);
The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>.
In your case, it would look like this:
scanf("%"SCNd64"", &n);
//...
if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);
It really is very ugly... but at least it is portable.
Your scanf() statement needs to use %lld too.
Your loop does not have a terminating condition.
There are far too many parentheses and far too few spaces in the expression
pi += pow(-1.0, e) / (2.0*e + 1.0);
You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
You should use an explicit return type of int for main().
On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.
I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.
First of all, %d is for a int
So %1.16lld makes no sense, because %d is an integer
That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.
What you want to use is the type double, for calculating pi
and then using %f or %1.16f.
// acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2
double pi = 2 * acos(0.0);
int n; // upto 6 digit
scanf("%d",&n); //precision with which you want the value of pi
printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

Resources