Functions different datatypes calculate rent - c

trying to make a function which calculate the total sum with rent of a starting amount.
My printf("%.1f", calcFutureValue[i]); don't want to work for some reason, i did a lookup if it had to do with the different datatypes, since numberOfYears is an int but not sure.
What i'am missing?
#include <stdio.h>
#include <math.h>
double calcFutureValue(double startingAmount, double interest, int numberOfYears);
int main()
{
double startingAmount = 10000;
double interest = 1.045;
int numberOfYears = 3;
calcFutureValue(startingAmount, interest, 3);
for (int i = 0; i < numberOfYears; i++)
{
printf("%.1f", calcFutureValue[i]);
}
getchar();
return 0;
}
double calcFutureValue(double startingAmount, double interest, int numberOfYears)
{
for (int i = 0; i < numberOfYears; i++)
{
startingAmount * interest * pow(numberOfYears, 2);
}
getchar();
}

Try this code:
#include <stdio.h>
#include <math.h>
double calcFutureValue( int numberOfYears);
const double startingAmount = 10000;
const double interest = 1.045;
int main()
{
int numberOfYears = 3;
int i;
for (i = 0; i < numberOfYears; i++)
{
printf("%.2f\n", calcFutureValue(i));
}
return 0;
}
double calcFutureValue(int numberOfYears)
{
return startingAmount * pow(interest, numberOfYears);
}
Explanation:
There was a mistake with the compound interest formula.
Since this is dealing with currency, the decimal width of 2 is appropriate.
Since startingAmount and interest are constants, they can be constant global variables.

Related

Reversing digit using recursive function in C

I'm trying to create a recursive function to reverse digits of a number in C. This is what I've written. It works fine when used one time but when used multiple times it keeps piling the numbers together. I think the problem can be sorted if the sum is initialized to zero each time the function is called but I'm unable to do it. I've tried declaring sum=0 as a global variable but the result was the same.
Input-
12
23
34
45
Output
21
2132
213243
21324354
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int digit_reverse(int N)
{
int rem;
static int sum=0;
if(N>0)
{
rem=N%10;
sum=sum*10+rem;
digit_reverse(N/10);
}
else
return 0;
return sum;
}
int main()
{
int a[25],i;
for(i=0;i<4;i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for(i=0;i<4;i++)
{
printf("%d\n",digit_reverse(a[i]));
}
}
Maybe you can write your function without using static variables:
void _digit_reverse(int N, int *sum)
{
int rem;
if (N > 0)
{
rem = N % 10;
*sum = *sum * 10 + rem;
_digit_reverse(N / 10, sum);
}
}
int digit_reverse(int N)
{
int sum = 0;
_digit_reverse(N, &sum);
return sum;
}
Or take the sum outside:
int sum = 0;
int digit_reverse(int N)
{
int rem;
if (N > 0)
{
rem = N % 10;
sum = sum * 10 + rem;
digit_reverse(N / 10);
}
else
return 0;
return sum;
}
int main()
{
int a[25], i;
for (i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for (i = 0; i < 4; i++)
{
sum = 0;
printf("%d\n", digit_reverse(a[i]));
}
}
I believe that the static variable gets initialized only once. This is the problem with your approach.
dude everything looks fine to me if the code do not needs to be reusable I can think of several solutions but keep in mind static and or global variables are not best practices unless necessarily required to.
secondly change your
// from static int sum = 0;
// to
static long sum = 0;
// or
static long long sum = 0;
the reason for this error is value overflow
an integer cannot have more than 4 bytes of data in this specific case you definitly needs more.

Function will not call correctly, C

I am a beginner and am doing pretty bad in my class right now, I just can't get some of this stuff down. I am working on one of the final homeworks and can't figure out the problem with my code. It's probably really messy but the main thing I'm having trouble with right now is the getArea function. It won't run correctly when I call it and says 'expected expression before int'. Any help is greatly appreciated, thanks
//This program takes 18 numbers and puts it in a single dimensional array and a two dimensional array.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define COLMAX 3
#define ROWMAX 6
double triArea(double a, double b, double c);
double checkValidation(double a, double b, double c);
double func1(double values[][COLMAX], int);
int main(void)
{
unsigned int seed;
double tArea = 0.0;
int rand_int();
int loop;
int col;
int row;
int counter = 0;
srand(time(NULL));
int RandomArray[18];
int ArrayTwo[6][3];
printf("\nOne dimensional array\n");
for(loop = 0; loop < 18; loop++)
{
RandomArray[loop] = rand_int();
printf("%d ", RandomArray[loop]);
}
printf("\nTwo dimensional array\n");
for(row = 0; row < ROWMAX; row++)
{
for(col = 0; col < COLMAX; col++)
{
ArrayTwo[row][col] = RandomArray[counter];
counter++;
//int total = 0;
//total = total + array2[row][col];
printf("%d\t", ArrayTwo[row][col]);
getArea(ArrayTwo[row][col]);
//printf("The total is %d", total);
}
printf("\n");
}
printf("\n");
double total = 0.0;
double ArrayTwoTotal[ROWMAX][COLMAX];
total = func1(ArrayTwoTotal, ROWMAX);
printf("total is %.2lf \n", total);
system ("PAUSE");
return 0;
}
double checkValidation(double a, double b, double c)
//triangleValueA + triangleValueB >= triangleValueC) && (triangleValueB + triangleValueC >= triangleValueA) && (triangleValueA + triangleValueC >= triangleValueB
{
int count = 0;
//a = base, b = height, c = area
if ((a + b >= c) && (b + c >= a) && (a + c >= b))
{
}
}
//Calculate area of a triangle
double getArea(int[int][int])
{
double base, height, area;
area = base*height/2.0;
printf("The area is %.lf\n", area);
checkValidation(base, height, area);
return area;
}
//Function to get the totals of the 1 dimensional array
double func1(double ArrayTwoTotal[][COLMAX], int rows)
{
double sum = 0.0;
int i, j;
for(i = 0 ; i < rows ; i++)
{
for(j = 0 ; j < COLMAX ; j++)
{
sum += ArrayTwoTotal[i][j];
}
}
return sum;
}
//Function to find a random number
int rand_int()
{
int x = 0;
x = ((rand() % 100)+1);
return x;
}
There are a lot of things that you need to look at.
First getArea() function doesn't have any declaration. Please declare it first and in a correct way.

CS50 readability result issue

I wrote the following code to solve the readability lab.
It is compiling well with no problem.
The problem is in the results, as for an unknown reason it always calculates s_avg as zero.
s_avg is the average number of sentences in 100 words.
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
//prototypes
int count_letters (string text);
int count_words(string text);
int count_sent(string text);
int main(void)
{
// get the user to prompt part of the story
string story = get_string("Text: \n");
//variables
int letters = count_letters(story);
int words = count_words(story);
int sentences = count_sent(story);
//show results
printf("%i letter(s)\n",letters);
printf("%i word(s)\n",words);
printf("%i sentence(s)\n",sentences);
// Calculate average number of letters & sentences per 100 words
int l_avg = (letters/words)*100;
int s_avg = (sentences/words)*100;
// Calculate Coleman-Liau index
int index = round(0.0588 * l_avg - 0.296 * s_avg - 15.8);
// check grade level
if(index<1)
{
printf("Before Grade 1\n");
}
else if(index>16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n",index);
}
}
//count the number of letters
int count_letters (string text)
{
int l = 0;
for(int i=0,n=strlen(text); i<n; i++)
{
if((text[i]>=97 && text[i]<=122)||(text[i]>=65 && text[i]<=90))
{
l++ ;
}
}
return l;
}
//count the number of words
int count_words(string text)
{
int w = 1;
for(int i=0,n=strlen(text); i<n; i++)
{
if (text[i]==32)
{
w++ ;
}
}
return w ;
}
//count the number of sentences
int count_sent(string text)
{
int s=0;
for(int i=0,n=strlen(text); i<n; i++)
{
if ((text[i]==46) || (text[i]==33) || (text[i]==63))
{
s++ ;
}
}
return s;
}
I don't know why it keeps calculating int s_avg = (sentences/words)*100; as zero.
I realized that using the debug50 tool.
For calculating average number of letters & sentences, use double type variables instead.
double l_avg = ((double)letters / (double)words)*100;
double s_avg = ((double)sentences / (double)words)*100;
Integer division in C results in an integer, not a float. You have to explicitly cast the dividend and the divisor to float:
int i = 5 / 4;
printf("%d", i); // prints 1
float f = (float)5 / (float)4;
printf("%f", f); // prints 1.250000
So, int s_avg = (sentences/words)*100 should be:
float s_avg = (float)sentences / (float)words * 100;

Why does same program act different in ideone and codeblocks?

This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.

Counting number of searches

I updated my main and sequetialSearch and now it crashes when it runs. It compiles okay, but then crashes.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include "percentage.h"
#include "sequentialSearch.h"
#define searchAmount 100
int main(int argc, char *argv[])
{
int numbers[100];
int searches[searchAmount];
int testAmounts[searchAmount];
int i;
int where;
int searchSuccess;
int searchUnsuccess;
int percent;
int looker;
int sum;
int average;
srand(time(NULL));
for (i = 0; i < 100; i++){
numbers[i] = rand() % 200;
}
for (i = 0; i < searchAmount; i++){
searches[i] = rand() % 200;
}
searchUnsuccess = 0;
searchSuccess = 0;
sum = 0;
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searchSuccess++;
testAmounts[i] = looker;
}else{
searchUnsuccess++;
testAmounts[i] = looker;
}
}
for(i = 0; i < searchAmount; i++){
sum = sum + testAmounts[i];
}
average = sum / searchAmount;
percent = percentRate(searchSuccess, searchAmount);
printf("Total number of searches: %d\n", searchAmount);
printf("Total successful searches: %d\n", searchSuccess);
printf("Success Rate: %d%%\n", percent);
printf("Total number of tests ran: %d\n", average);
system("PAUSE");
return 0;
}
sequentialSearch.h
bool seqSearch (int list[], int last, int target, int* locn, int* looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
*looker++;
}
*locn = *looker;
return(target == list[*looker]);
}
Pass looker in by reference, so that you can access its value from the caller.
int looker;
...
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searches[i] += looker;
searchSuccess++;
}else{
searchUnsuccess++;
}
}
bool seqSearch (int list[], int last, int target, int* locn, int *looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
(*looker)++;
}
*locn = *looker;
return(target == list[*looker]);
}
By the way, you may wish to reconsider defining functions in your header file; this could cause problems with duplicate symbol when linking if you have more than one c file including this file.
Why not just pass looker in as an int*, use it essentially as you have been, look at the value after seqSearch(...) returns, and add it to a running total back in main()?
One problem is that the increment of looker in seqSearch is incrementing the pointer rather than the value. It should probably be:
(*looker)++;

Resources