I am taking my first programming class this semester and I can't figure out what is going on with my program. I have to write a program that calculates the total amount of money after so many years with interest. The formula is y=p*(1+r)^n
Anyways, whenever I run my code it comes up as "_ has stopped working" and closes.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main (void)
{
double p, r, n, y;
printf("Enter the interest rate>");
scanf("%lf", r);
printf("Enter the principle amount of money invested>");
scanf("%lf", p);
printf("Enter the number of years invested>");
scanf("%lf", n);
y = pow(p*(1+r),n);
printf("The total amount of money is %f.\n", y);
system("PAUSE");
return (0);
}
I have tried googling it and it seems like it might have something to do with "initializing", but I'm not sure what that means or how to do it. Any help is greatly appreciated!
First of all the scanf() function expects the adress of a variable not the variable itself, so it should be used like that scanf("%lf", &r);Try it and you will be okay
And secondly never use system("PAUSE")!!
It is platform specific (windows) and it is wrong system("pause"); - Why is it wrong?
You are learning to program in a wrong way by using system(PAUSE) and in the above link you can see why!
This code was written and tested on linux platform.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main (void)
{
double p, r, n, y, value;
int a = 3, b = 2;
printf("Enter the interest rate>");
scanf("%lf", &r);
printf("Enter the principle amount of money invested>");
scanf("%lf", &p);
printf("Enter the number of years invested>");
scanf("%lf", &n);
value = p * (r + 1);
y = pow(value, n);
printf("The total amount of money is %f.\n", y);
//system("PAUSE");
return (0);
}
to compile this code in linux use,
gcc code.c -lm
I dont know why, I am forced to include -lm at compile time even though I am adding #include. Any one feel free to update the answer on this.
Update.
Please see this answer for why we must use -lm Undefined reference to 'pow' even though -lm is a compile flag. [C]
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I've completed my latest assignment last night in Dev C++, which is what we are required to create it in. Got it working flawlessly, compiles great, runs great, everything is fine. However, we have to run our program through 'MobaXTerm' and through a VPN, using our University's system that they use to grade on. I tried to run it and I get an error, 'segmentation fault'. That was the first time I heard of the error so I researched it. In most cases, it's putting the wrong variable in a 'for loop' but I checked my loops 50 times, it works. I assume it has something to do with my 2D array, maybe going out of bounds, but I debugged, and from what I can tell, it doesn't escape the size that I assigned for it.
I don't exactly just want to paste my whole program in here but I'll give a few snippets and maybe someone could try to tell me what might possibly be the issue. I just don't really understand how it runs fine in one and not the other.
#include <stdio.h>
#include <stdlib.h>
#define ROWS 12
#define COLS 8
void makeArray(FILE*, int [][COLS]);
int getScore(int [][COLS], int, int);
int getMonthMax(int [][COLS], int);
int getYearMax(int [][COLS]);
float getMonthAvg(int [][COLS], int);
float getYearAvg(int [][COLS]);
int toursMissed(int [][COLS]);
void displayMenu();
int processRequest(int [][COLS], int);
void printArray(int [][COLS]);
int main(){
int scoresArray[ROWS][COLS];
int choice, constant = 0;
FILE *scoreFileptr;
scoreFileptr = fopen("scores.txt", "r");
if (scoreFileptr == NULL)
printf("The file isn't opening");
makeArray(scoreFileptr, scoresArray);
while(constant == 0){
displayMenu();
scanf("%d", &choice);
processRequest(scoresArray, choice);
}
fclose(scoreFileptr);
}
Here's a function:
void makeArray(FILE *scoreFileptr, int scoresArray[][COLS]){
int i, j, filler = 0;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
fscanf(scoreFileptr, "%d", &filler);
if(filler == 999){
break;
}
scoresArray[i][j] = filler;
}
}
}
Here's another function:
int processRequest(int scoresArray[][COLS], int choice){
int month = 0, tourNum = 0;
switch(choice){
case 1:
printf("Please enter the month and the game\n");
scanf("%d %d", &month, &tourNum);
printf("The score for tournament %d is %d\n\n",tourNum, getScore(scoresArray, month, tourNum));
break;
case 2:
printf("Please enter the month\n");
scanf("%d", &month);
printf("The max score in month %d is %d\n\n", month, getMonthMax(scoresArray, month));
break;
case 3:
printf("Please enter the month\n");
scanf("%d", &month);
printf("The average score for month %d is %.2f\n\n", month, getMonthAvg(scoresArray, month));
break;
case 4:
printf("The max score for the year is %d\n\n", getYearMax(scoresArray));
break;
case 5:
printf("The average score for the year is %.2f\n\n", getYearAvg(scoresArray));
break;
case 6:
printf("The number of tournaments missed for the year is %d\n\n", toursMissed(scoresArray));
break;
case 7:
printf("The scores for the year are:\n");
printArray(scoresArray);
break;
case 0: printf("Thank you! Goodbye");
exit(0);
break;
default:
printf("Please enter one of the options listed\n\n");
}
return 0;
}
Do you think it's the way I'm passing the array to the functions? That's the only way I can think of. But then why would it work in the Dev C++ compiler? I'm stumped.
Edit: The problem seems to be in the 'makeArray' function. I took out the function call for it in main and it runs now. Just got to figure out what's causing it.
Edit 2: After going through the function line by line, they problem seems to be the 'fscanf' line in the makeArray function. Thank you all for pointing me in the right direction!
Since the whole code is not available, I'll tell you the cause and what to look for, but I can't provide an exact answer.
In C there is a thing called undefined behavior. What this means is that the standard does not guarantee what happens in that case. It may work, it may fail at runtime, basically anything can happen.
The most common undefined behavior errors that are encountered are memory related errors. For example, assume the following code snippet:
int a[10];
a[10] = 2;
I access an element outside the allocated region of the array a. This is undefined behavour according to the standard, so there is no hint about what can happen. In practice, there are usually 2 outcomes: it can run almost fine or it can produce a segmentation fault, depending on the compiler.
Why it depends on the compiler? Well, this kind of code goes into the stack memory area, which is managed by the compiler. In some cases, overwriting the memory location after the array might not overwrite an important memory region of the program, and the program can finish executing. In other cases, the compiler decides to put some important data just after the array (like a stack pointer), which, if overwritten, makes the program to crash. Also, there might be some protected memory region after that array or you may corrupt the value of another variable you plan to use.
(I described just some common possible outcomes of this. There are other problems this type of errors can cause).
It just happens that the code compiled with Dev C++ can run with this error. Note that this is not a good thing by no means - undefined behaviors should be avoided at any cost.
As I said, it's pretty hard to say where is actually the problem. Just a few hints for debugging: try to remove some parts of the code until it works, then add piece by piece and try to locate the line(s) where the error occurs.
P.S. Also, make sure you have the input file available.
#include <stdio.h>
#include <stdlib.h>
#define ROWS 12
#define COLS 8
void makeArray(FILE* scoreFileptr,int (*scoresArray)[COLS]);
int main(){
int scoresArray[ROWS][COLS];
int choice, constant = 0;
FILE* scoreFileptr = fopen("scores.txt", "r");
if (scoreFileptr == NULL){
printf("The file isn't opening\n");
}else{ printf("opened\n");}
makeArray(scoreFileptr,scoresArray);
//printf("%d\n",scoresArray[0][3]); test
fclose(scoreFileptr);
}
void makeArray(FILE* scoreFileptr,int (*scoresArray)[COLS]){
int i, j, filler = 0;
for(i = 0; i < ROWS; i++){
for(j = 0; j < COLS; j++){
fscanf(scoreFileptr, "%d", &filler);
if(filler == 999){
break;
}
scoresArray[i][j] = filler;
}
}
}
This is the piece of your code that I have modified a bit and it's working (compiled with gcc). Hope it can help. As you can see, since your function is void I passes the address of the 2D.
here is the code as written in visual studio
#include <stdio.h>
void main()
{
int n,i,num,s;
float av;
printf("How Many numbers?");
scanf("%d",&n);
s=0;
for(i=1;i<=n;i++){
printf("enter number #%d : ",i);
scanf("%d", &num);
s=s+num;
}
av=s/n;
printf("The Average is %f",av);
getchar();
}
i really don't know why it isnt displaying the right average :/
The problem is here: av=s/n; you are storing the result of an integer division into a float, there will be some data loss. A simple solution: use typecasting->
av=(float)s/n;
or
av=s/(float)n;
Another alternative: make either s or n a float.
av=s/n; Lookup "integer division". You probably want to use av=(float)s/n;
Division of two integer values doesn't automatically convert to a float value, unless you use a cast.
um hello, well I tried to compile my code and it works fine, then run it, at first its working, until I input a character it suddenly crash. Do you know whats wrong with it? BTW Im just a beginner in programming so any suggestions or criticize is welcome. Thanks!
#include <stdio.h>
int main ()
{
char w;
int a, b;
float cola, change, rb, pep;
printf("Welcome! Please choose your drink from these beverages! Press the following buttons to order; \nA - Cola \nB - Root Beer \nC - Pepsi \n");
scanf("%c", w );
if(w=='A'){
printf("\nYou chose Cola!\n This cost $0.75.\n How many would you like to buy?");
scanf("%d", &a);
cola=a*.75;
printf("\nYou bought %d cola/colas. That will be %f. How much is your money?/n", a,cola);
scanf("%d", b);
change=b-cola;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else if(w=='B'){
printf("\nYou chose Root Beer!\n This cost $1.00.\n How many would you like to buy?");
scanf("%d", &a);
rb=a*1.00;
printf("\nYou bought %d root beer/beers. That will be %f. How much is your money?/n", a,rb);
scanf("%d", b);
change=b-rb;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else if(w == 'C'){
printf("\nYou chose Pepsi!\n This cost $1.50.\n How many would you like to buy?");
scanf("%d", &a);
pep=a*1.50;
printf("\nYou bought %d pepsi/s. That will be %f. How much is your money?/n", a,pep);
scanf("%d", b);
change=b-pep;
printf("\nYour change is %f.\n Please come again!\n", change);
}
else{printf("Please come again./n");}
return 0;
}
These lines:
scanf("%d", b);
scanf("%c", w );
will crash. You need to pass a pointers to b and w instead:
scanf("%d", &b);
scanf("%c", &w );
The scanf function takes an address in memory as argument, in other words your input value needs a place in memory to store and for that you need to give an address,
http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm here will explain more about it.
Suggestion:If you will continue programming in your life, you should start naming the variables better, for example in your case : a should be numberOfDrinks and b should be moneyAmount or something similar, you will see when you will be working on a bigger project how important this is
Suggestion/Tip:You should start learning how to work in a modular way, meaning you should use functions , because it's best practice and you can reuse the code as many times as you like in the program, and it's easier to test also.
I have this problem with this homework I'm supposed to do.
[ It says Create a program that's able to calculate and show the sum of S]
Like S=1+1/4+1/8+1/16 ... till 1/ [2 pow n]
So I worked on it and came up with this code
#include <stdio.h>
void main()
{
int n,i;
float p,s;
printf("Enter the maximum power n :");
scanf("%d",&n);
s=0;
p=0;
for (i=0;i<n;i++)
{
p+=1/pow(2, i);
s+=p;
printf("s = %f\n",s);
}
printf("The sum of this equation is :%f",&s);
}
But when I execute it is always like S=0.
What am I doing wrong?
You are printing an address ('&s) with%f` variable. Using a wrong specifier invokes undefined behavior. You may get anything.
Also, No need of variable s. Remove the line
s+=p;
It should be like:
#include <stdio.h>
int main(void)
{
int n,i;
float p;
printf("Enter the maximum power n :");
scanf("%d",&n);
p=0;
for (i=0;i<n;i++)
{
p+=1/pow(2, i);
printf("p = %f\n",p);
}
printf("The sum of this equation is :%f",p);
}
You need to include <math.h> to get the proper prototype of pow().
You might need to link to the math library too gcc main.c -Wall -lm
#include <math.h>
....
for (i=0;i<n;i++)
{
p=1/pow(2, i);
s+=p;
printf("s = %f\n",s);
}
printf("The sum of this equation is :%f",s);
Your program has multiple problems. Enabling compiler warnings should tell you about some of them.
You should include the C header which contains the declaration of the pow function.
You add each addend twice.
In your second printf statement, you pass a float. But the %f format specifier expects a double argument. In your third printf statement, you pass a pointer to a float.
Another cosmetic problem is that your main function should return an int.
just a guess, may you replace the line
p+=1/pow(2, i);
with
p+=1.0f/(float)pow(2, i);
and
printf("The sum of this equation is :%f",&s);
with
printf("The sum of this equation is :%f",s);
Typo may be.. but you will have say %f and s (not &s)
printf("The sum of this equation is :%f",s);
On side note:
Once you include <math.h> you will get compiler warning for using correct pow(..) prototype. Below code would be relevant.
p+=1.0f/(float)pow(2.0f, i);
//A program that calculates the amount of money in a bank account after n years
#include <stdio.h>
double bank(double money, double apy, int years);
int main() {
double money1, apy1;
int years1;
printf("How much money is currently in your bank account? ");
scanf("%d", &money1);
printf("How many years will this money stay in your account? ");
scanf("%d",&years1);
printf("What is your APY? ");
scanf("%d", &apy1);
int bank1 = bank(money1, apy1, years1);
printf("Your grand total after %d will be $%d \n", years1, bank1);
system ("PAUSE");
return 0;
}
double bank(double money, double apy, int years) {
if(years <= 0)
return money;
else
return bank(money*apy, apy, years-1);
}
Change:
scanf("%d", &money1);
to
scanf("%lf", &money1);
and change:
scanf("%d", &apy1);
to:
scanf("%lf", &apy1);
And while you're at it you might want to add some printfs to help with debugging (assuming you don't have a source level debugger.)
This:
return bank(money*apy, apy, years-1);
should probably be
return bank(money*(1+apy), apy, years-1);
since the interest you earn should be added to the existing amount. Otherwise your total amount would be reducing each year.
Another one is :
double bank(double money, double apy, int years);
Returns a double, but
int bank1 = bank(money1, apy1, years1);
You place the result in an int.
You should never use floating point in financial calculations.
Floating point is inherently uncapable of representing 10-base values precisely, which means that you will suffer from rounding errors and unequalities, which is unacceptable in finances (among others).
This has been discussed in detail many times on SO. The issue is not language specific.
I think you should call you function in the following way:
int bank1 = bank(money1, 1+apy1/100., years1);
Otherwise you'll have a LOT of money :)