Why is this returning -nan? - arrays

#include <stdlib.h>
int main()
{
int i,j;
float averageyear;
float averagemonth;
float sumyear;
float rainny;
int year = 2020;
int rain[5][12];
const char* month[12] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
for (i=0;i<5;i++)
{ printf("*****Year %d*****\n",year+i);
for (j=0;j<12;j++)
{
printf("%s: ",month[j]);
scanf("%f",&rainny);
sumyear+=rainny;
averageyear=(float)sumyear/12;
}
printf("Total of %d is %.2f\n",year+i,sumyear);
//averageyear=(float)sumyear/12;
printf("Average of %d is %.2f\n",year+i, averageyear);
sumyear=0;
}
}
The code gives me the output
Total of 2020 is -nan
Average of 2020 is -nan
But when I switch averageyear=(float)sumyear/12; to outside the for loop (The commented line), it gives me the right output. I don't see any difference between those 2 positions of the code. Please help me clarify this. Thank you!

Without initializing variables declared in block-scope (like sumyear) they contain whatever the memory had present prior to the program running.
If this value was not a number, which is a special number in floating point representations to handle things that aren't rational numbers, then adding anything to it will also yield NAN (not a number).
Initialize the sumyear (and your other variables) to valid values, and your program will work correctly regardless of whatever memory it is assigned to use.

Related

Square root values not being retrieved

I'm having a problem with getting my code to pick up the user input of the variables number and result. The correct way the code should act is: When user puts in a positive value, code should square root this value and display the new value. As of now, there are no error messages, the code runs fine, just not the way i want it to.
It does NOT pick up any value and does not square root math either, when looking at the output.
I also need to use pointers when doing this code (weird imo). Pointers are something im very new to so i expect to get quite the critique on that department.
I have tried reading several tutorials on pointers and the understanding of sqrt but it feels like key parts of those things still confuse me.
Code: (Consists of a function squareRoot that does the math and main that handles input/output)
#include <stdio.h>
#include <math.h> //needed for sqrt()
#define POSITIVE 1 //not used atm
#define NEGATIVE 0 //not used atm
float squareRoot(float number, float * result) {
return * result = sqrt(number); //calculate the square root of a number
}
int main() {
float number = 0;
float * result = malloc(sizeof(float));
printf("Enter a float value: ");
scanf("%f", &number);
squareRoot(number, result);
if (number < 0) {
printf("Square root of a negative value is not possible.");
}
if (number > 0) {
printf("Square root if %.2f is: %.2f "), number, result;
}
return 0;
}
Any help or constructive criticism is greatly appreciated!
result is a pointer, you need to dereference it.
printf("Square root if %.2f is: %.2f ", number, *result);
If you didn't get a compiler warning for the type mismatch, increase your warning level.

Not able to calculate in C.How do you calculate in 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.

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.

Determining if a float has a fractional part?

Here is the problem: The game Totals can be played by any number of people. It starts with a total of 100 and each player in turn makes an integer displacement between -20 and 20 to that total. The winner is the player whose adjustment makes the total equal to 5. Using only the three variables given:
total
adjustment
counter
Here is what I have so far:
#include <stdio.h>
int main (void)
{
int counter=0;
float adj;
int ttl=100;
printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");
while (ttl!=5)
{
printf("YOUR ADJUSTMENT?");
scanf("%f",&adj);
counter++;
if (adj<=20 && adj>=-20)
{
ttl=ttl+adj;
printf("The total is %d\n",ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
printf("The game is won in %d steps!",counter);
}
What I need:
When a decimal number is entered it goes to the else. How do I determine if a float has a fractional part.
You can cast the float to an int and then compare it to your original variable. If they are the same there was no fractional part.
By using this method, there is no need for a temporary variable or a function call.
float adj;
....
if (adj == (int)adj)
printf ("no fractional!\n");
else
printf ("fractional!\n");
Explanation
Since an int cannot handle fractions the value of your float will be truncated into an int (as an example (float)14.3 will be truncated into (int)14).
When comparing 14 to 14.3 it's obvious that they are not the same value, and therefore "fractional!" will be printed.
#include <stdio.h>
#include <math.h>
int main ()
{
float param, fractpart, intpart;
param = 3.14159265;
fractpart = modff (param , &intpart);
return 0;
}
http://www.cplusplus.com/reference/clibrary/cmath/modf/
modff finds the fractional part, so I guess testing whether it's equal to 0 or null will answer your question.
if you want to know whether a real number x has no fractional part, try x==floor(x).
I am only learning C so tell me if I am wrong, please.
But if instead of using
scanf("%f",&adj);
if you use:
scanf("%d%d", &adj, &IsUndef);
Therefore if the user typed anything other than a whole integer &IsUndef would not equal NULL and must have a fractional part sending the user to else.
maybe.
Using scanf() is problematic. If the user typed -5 +10 -15 -15 on the first line of input, then hit return, you'd process the 4 numbers in turn with scanf(). This is likely not what you wanted. Also, of course, if the user types +3 or more, then the first conversion stops once the space is read, and all subsequent conversions fail on the o or or, and the code goes into a loop. You must check the return value from scanf() to know whether it was able to convert anything.
The read-ahead problems are sufficiently severe that I'd go for the quasi-standard alternative of using fgets() to read a line of data, and then using sscanf() (that extra s is all important) to parse a number.
To determine whether a floating point number has a fractional part as well as an integer part, you could use the modf() or modff() function - the latter since your adj is a float:
#include <math.h>
double modf(double x, double *iptr);
float modff(float value, float *iptr);
The return value is the signed fractional part of x; the value in iptr is the integer part. Note that modff() may not be available in compilers (runtime libraries) that do not support C99. In that case, you may have to use double and modf(). However, it is probably as simple to restrict the user to entering integers with %d format and an integer type for adj; that's what I'd have done from the start.
Another point of detail: do you really want to count invalid numbers in the total number of attempts?
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter=0;
int ttl=100;
printf("You all know the rules now lets begin!!!\n"
"\n\nWe start with 100. What is\n");
while (ttl != 5)
{
char buffer[4096];
float a_int;
float adj;
printf("YOUR ADJUSTMENT?");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
break;
if (sscanf("%f", &adj) != 1)
break;
if (adj<=20 && adj>=-20 && modff(adj, &a_int) == 0.0)
{
counter++; // Not counting invalid numbers
ttl += adj;
printf("The total is %d\n", ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
if (ttl == 5)
printf("The game is won in %d steps!\n", counter);
else
printf("No-one wins; the total is not 5\n");
return(0);
}
Clearly, I'm studiously ignoring the possibility that someone might type in more than 4095 characters before typing return.

Resources