I'm trying to calculate a price decrease based on percentages. If I write it out by hand, it comes out like the equation below, a simple x = x - (10% of x) , or new_price = old_price - (10% of old_price). So 100 would become 90, 90 would become 81, and so on. I think. I'm not sure if I'm brainfarting or what, but when I run this, it just forever loops "90" as output.
#include <stdio.h>
#include <math.h>
int pricedecrease(int x)
{
x = x - (x / 10.0);
return x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", pricedecrease(price));
}
}
You need to update your price variable in the loop. Calling the pricedecrease function will not modify the price variable.
#include <stdio.h>
#include <math.h>
int pricedecrease(int x)
{
x = x - (x / 10.0);
return x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", price);
price = pricedecrease(price); // <- need to update price variable
}
}
Function parameters are passed by value in C, and so the function body does not affect the value of the parameter when the function returns to the caller.
In your case, you return the adjusted value as a return value, so you can assign the return value to your variable.
while (price > 3)
{
price = pricedecrease(price);
printf("%d\n", price);
}
It's an infinite loop because price is not modified.
Function parameters are passed as a copy onto the stack. In order to modify the original, you'll need to use pointers and pass the address of price.
int pricedecrease(int *x)
{
*x -= (*x / 10.0);
return *x;
}
int main(void)
{
int price = 100;
while(price > 3)
{
printf("%d\n", pricedecrease(&price));
}
}
Related
#include<stdio.h>
const char *author ="Alexandre Santos";
int succ(int x)
{
return x+1;
}
int pred(int x)
{
return x-1;
}
int is_zero(int x)
{
return x == 0;
}
int is_pos(int x)
{
return x >= 0;
}
int sum(int x, int y)
{
return is_zero(y)? x: sum(succ(x),pred(y));
}
int twice(int x)
{
return sum(succ(x), pred(x));
}
int main(void)
{
int x;
scanf("%d", &x);
int z = twice(x);
printf("%d\n", z);
return 0;
}
I am in the first year of university and this is one of the exercises that a professor gave. I need to calculate the double of a number just using the given functions(succ, pred, is_zero, is_pos). I tried to do it and managed to come up with a solution but to be honest I don't understand how this is working. My main doubt is how the sum function is working since it uses the variable y and in this program this variable doesn't even exist/is not inserted in the input. Any tip?
In your code, you called the function twice() with the parameter x, and in the function twice() you called the function sum() with the parameters succ(x) and pred(x), the value of succ(x) is assigned to x in sum, and the value of pred(x) is assigned to y in sum.
So for example; you passed the value 10 to x in the input, we will call the function twice with a value 10, and twice(10) returns the sum of succ(10) and pred(10) which are 11 and 9, so the values 11 and 9 are passed to the function sum like this: sum(11, 9), so in the function sum, the parameter x gets the value 11, and the parameter y gets the value 9.
Compute the sum of the two given integer values. If the two values are the same, then return triple their sum.
int main() {
printf("%d\n", test(1, 2));
printf("%d", test(2, 2));
}
int test(int x, int y) {
int sum;
if (x == y) {
sum = (x + y) * 3;
printf("sum = %d\n", sum);
} else {
sum = (x + y);
printf("sum = %d", sum);
}
}
When I run this code, I get the wrong output, but when I use return statements instead of the printf, I get the right input. Why?
Since test does not return a value (there is no return statement), the attempt to reference the return value results in undefined behavior. It might be easier to understand what is happening in your program if you make a few minor modifications:
#include <stdio.h>
int
test(int x, int y)
{
int sum = x + y;
if( x==y ){
sum *= 3;
}
printf("sum = %d XXX ", sum);
return sum;
}
int
main(void)
{
printf("** %d **\n", test(1, 2));
printf("** %d **\n", test(2, 2));
return 0;
}
The output of the above program is:
sum = 3 XXX ** 3 **
sum = 12 XXX ** 12 **
The test in the argument list to printf in main is called before the printf in main can be called. The printf inside the test function executes and prints sum = ... XXX . The function returns a value which is passed as an argument to the printf in main which prints ** ... **.
Your program is just a little bit wrong. Keeping with the general structure of your code, here are two ways that you can rewrite it.
#1: Instead of returning a value, the test function prints a value. Since test does not return a value, you must put the keyword void before the function name. To get the values to print, the main function must call the test function.
int main() {
/** calls the test function,
then the test function prints
the sum value **/
test(1,2);
test(2,2);
return 0;
}
void test(int x, int y) {
int sum;
if (x == y) {
sum = (x + y) * 3;
printf("sum = %d\n", sum); /** prints the sum value**/
} else {
sum = (x + y);
printf("sum = %d", sum); /** prints the sum value**/
}
}
#2 The test function returns the sum value. Since sum is an int, you must put the keyword int before the function name. The main function gets the value of sum by calling the test function. Then main prints this value.
int main() {
/** prints the value returned
by the test function **/
printf("%d\n", test(1,2));
printf("%d", test(2,2));
return 0;
}
int test(int x, int y) {
int sum;
if (x == y) {
sum = (x + y) * 3;
} else {
sum = (x + y);
}
/** returns the value of sum **/
return sum;
}
Consider my attempt to implement the Babylonian method in C:
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
Result is for x=27: 0.0000?
Where is my mistake?
While the function returns an int, that value is printed with the wrong format specifier, %f instead of %d.
Change the signature (and the name, if I may) into something like this
double cube_root(double x) { ... }
Or change the format specifier, if you really want an int.
Following the explanation from tutorialspoint, which states, that the basic idea is to implement the Newton Raphson method for solving nonlinear equations, IMHO, the code below displays this fact more clearly. Since there is already an accepted answer, I add this answer just for future reference.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
Here, in contrast to the original code of the question, it is more obvious, that x and y are the bounds, which are being improved until a sufficiently accurate solution is found.
With modification of the line in the while block, where y is being updated, this code can also be used to solve similar equations. For finding the square root, for example, this line would look like this: y = a / x.
I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs.
I have this and i think it should work but i'm not entirely sure why its not
#include <stdio.h>
int main()
{
int sum (x, max);
int total, y, x, max;
if (x<max){
y=x+1;
total = x+sum(y,max);
return total;
return x;
}
return 0;
}
Thanks for any help with this in advance!
Here is one possible solution:
#include <stdio.h>
int sum_in_range(int a, int b){
if(a != b){
return sum_in_range(a+1,b)+a;
}
else{
return b;
}
}
int main(void) {
// your code goes here
printf("%d",sum_in_range(2,4));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int sum(int s,int max)
{
if(s==max)
{
return s;
}
else
{
return(s+sum(s+1,max));
}
}
int main()
{
int r,s,max;
printf("\n enter s and max");
scanf("%d%d",&s,&max);
r=sum(s,max);
printf("%d",r);
}
I spotted some errors on your code. I'm not a pro yet but here's what I think
I just edit your code. removed, added and rearranged some stuff*/
/*First, let's look at your code*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum(x, max);//I think what you want to do here is declare a function but instead declaring, you define it here because you added semicolon (;)
int total, x, y, max;
if(x < max)
{
y = x + 1;
total = x + sum(y, max); //you don't have a function declaration for "sum"
return total;
return x; //this will never return since you already "return the total before this"
}
return 0;
}
//////////////////////////////////////////////////////////////
/*And I think this is what you want to do*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6; //We declare this here for the "sum" function. This way "sum" function can recognize these variables
int total = x; //be sure to set the total to x.
//you can make a void function for this instead of "int". but either way, it can do the job.
void sum(int y) //no need to pass a "max" because "max" is already recognized by the "sum" function since we declare the variables at the top of "main" function
{
if(x < max)//don't make it x <= max. Because of the argument "total = total + (x + 1)" on this function. If you do, the total will exceed.
{
//You can see here why we set the value of "total" to x.
total = total + (x + 1);//And also, you can see why we didn't make the argument in if() statement like this: if(x <= max).
x++;//increment "x" every loop
//call the function again and pass the total until x == max.
sum(total);
}
}
//pass the x
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
//////////////////////////////////////////////////////////////
/*It looks messy with comments*/
/*Here's the code looks like without a comment.It's pretty short code if you look remove the comments.. LOL..*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6;
int total = x;
void sum(int y)
{
if(x < max)
{
total = total + (x + 1);
x++;
sum(total);
}
}
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
Im trying to make a program that calculates out a math equation, Im getting stuck on how i generate a random number from 0.00 to 1.00 and store it in a variable a.
this is my code so far, im stuck to how now take that number and store it for future use. I need to store that random number in a, and hten use it in a loop, and then generate a new random number and use it in the 2nd cycle of the loop.
EDIT
this is what i have been working on now, it is suppose to calculate the number of times a random number is inside the area, count it, and then devide by the number of times run, but im not getting any output
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));
while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
}
printf("%f", calculatedpi);
}
There are a few issues with your code:
You shouldn't use nested functions. Some compilers support them as an extension but it's not standard. Define randfloat and initrand outside main
The function initrand does too little. Why not call srand((time(0)); from main ?
Your initrand function is declared as returning a double but it doesn't return anything (and the way it's named it shouldn't). If you need to use such a function, why not make it return void ?
You should rarely use float. Why not use double ?
That said, you can do this to store that random value:
double randdouble()
{
return rand()/((double)RAND_MAX + 1);
}
int main()
{
double x = randdouble();
/* ... */
}
I think you want something like this:
#include <stdlib.h>
#include <time.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
initrand();
float a = randfloat();
return 0;
}
You can't nest functions like in some other languages.
You had non-matching parentheses in the initrand function.
I fixed the declarations of your functions, use void when there are no parameters, initrand doesn't return anything.
Your division by RAND_MAX+1 was a little messed up. Simply divide by RAND_MAX and the result will be in the closed interval [0,1]. And the syntax for the conversion to float was not quite right.
If you want to get random double numbers in a specified range you can use this function
// Return a random double from a to b
double randomDouble(double a, double b)
{
return = ( rand() / ( (double)RAND_MAX + 1.0))
* (b - a) + a;
}