Factorial with while loop in C [duplicate] - c

This question already has answers here:
When should I use ampersand with scanf()
(3 answers)
Closed 3 years ago.
Hello friendly community,
i´m really new in coding and also here registred on stackoverflow, so excuse me when I ask such simple questions. I lack the understanding to understand why this code does not work, because even after compiling no error message appears.
My Code below shows my try to code a while loop, calculating the factioral and printing the total:
#include <stdio.h>
/* Factorial 5! = 5*4*3*2*1 */
main ()
{
int Wert;
int fak = 1;
scanf ("%d", Wert);
while ( Wert > fak) {
fak = fak * Wert;
Wert = Wert - 1;
printf ("%d", fak);
}
}
It should calculate the factorial after input of a number and print the total. Maybe this can´t work but i don´t understand the why.
Thank you for your time.

Firstly, scanf expects the address of Wert, not its value, and also update your while loop to compare with 1. Here's the fixed version:
#include <stdio.h>
int main(void)
{
int Wert;
int fak = 1;
scanf ("%d", &Wert);
while ( Wert > 1 ) {
fak = fak * Wert;
Wert = Wert - 1;
}
printf ("%d", fak);
}
Input:
5
Output:
120
But since factorials easily overflow integers, it may be a better idea to use double instead:
#include <stdio.h>
double fact(double d)
{
if (d < 1.0)
return 1.0;
return d * fact(d - 1.0);
}
int main(void)
{
double d = 0;
if (scanf("%lf", &d) != 1) {
perror("Failed to read stdin");
return -1;
}
printf("%lf! = %lf", d, fact(d));
return 0;
}
Input:
100
Output:
100.000000! = 93326215443944102000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
Just keep in mind that floating point math is broken.

Related

What has got to come to the print function after the colon,? [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed last month.
#include <stdio.h>
int folgenglied(int);
int main(){
int n, m;
printf("Type a number in\n");
scanf("%d", &n);
m = folgenglied(n);
printf("%d ist the Folgenglied", m);
}
int folgenglied(int n) {
int x;
x = 1 / (n + 2);
return x;
}
I want to write the result of the folgenglied in the second printf call, but it always prints out 0. I don’t understand what’s wrong with my code.
I would start from the proper formating.
Function return value. You can use this value.
Always check the result of the scanf function
Integer division will return 0, -1, or 1 (abstracting from the division by zero)
#include <stdio.h>
double folgenglied(int);
int main(void)
{
int n,m;
double result;
printf("Type a number in\n");
if(scanf("%d", &n) == 1)
{
result = folgenglied(n);
printf("%f ist the Folgenglied", result);
}
}
double folgenglied(int n )
{
double x = 0.0;
if(x != -2) x=1.0/(n + 2);
return x;
}

Custom program to calculate sqare root isn't showing any output [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
This is a user defined program to print the square root of a number. It is supposed to work for numbers which aren't perfect squares as well. i is incremented by a step of 0.01 each time and the the value of i*i is checked if equal to n. And if equal then the value of i is printed.
#include <stdio.h>
void squareRoot(double);
int main()
{
double num;
scanf("%lf", &num);
squareRoot(num);
return 0;
}
void squareRoot(double n)
{
double i;
for (i = 0; i < n; i += 0.01)
{
//printf("%.2lf\n",i*i);
if (i * i == n)
{
printf("%lf\n", i);
break;
}
}
}
The method you use is, at best, very inaccurate for the reasons explained in the comments, there are several ways to calculate a square root, for this sample I'll use the Babylonian method which in its simplified form is very easy to implement using trivial arithmetic operations:
Running sample
#include <stdio.h>
double squareRoot(double);
int main() {
double num;
printf("Enter number: \n");
scanf("%lf", &num);
if(num < 0) {
puts("Negative values not allowed");
return 1;
}
printf("Square root of %.2lf is %lf", num, squareRoot(num));
}
double squareRoot(double num) {
double sqroot = num / 2, temp = 0;
while (sqroot != temp) {
temp = sqroot;
sqroot = (num / temp + temp) / 2;
}
return sqroot;
}

What can i do to make integer random everytime [duplicate]

This question already has answers here:
How to generate a random int in C?
(32 answers)
Closed 3 years ago.
I created a little guessing game, where you need to guess a number in 3 tries or you will fail. Now question is what can i do to make integer random every time i run program.
Here is a code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sN = 4;
int g;
int gC = 0;
int gL = 3;
int ofG = 0;
while(g != sN && ofG == 0)
{
if(gC < gL)
{
printf("Guess a number[1-10]: ");
scanf("%d", &g);
gC++;
}
else
{
ofG = 1;
}
}
if(ofG == 1)
{
printf("You Failed! [Out of guesses]\n");
printf("Secret number was (%d)\n", sN);
}
else
{
printf("Congratulations! You win!");
}
return 0;
}
Show me how i can do it and explain what you did and what command/function does if you can because i'm new and i don't understand things very well. I guess i need to use
srand();
but i never used it before so any help would be appreciated.
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
/* random int between 0 and 9 */
int r = rand() % 10;

scanf requires more inputs than requested [duplicate]

This question already has answers here:
Store data in array from input [duplicate]
(2 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 9 years ago.
I'm trying to get 5 float values from the user using scanf, the problem is the user is required to input 6 values for the program to complete.
Although I know I shouldn't use scanf, it bothers me that there's something I can't grasp about it. Any insights, any advice on how to fix it whilst using scanf?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0 , j = 0;
char buf[128] = {0};
float numbers[5] = {0.0};
float keep = 0.0;
printf("Please input 5 numbers : \n");
for (i = 0; i < 5; i++)
{
scanf("%f\n", &numbers[i]);
}
printf("Done!");
Thanks,
MIIJ
you must remove \n in scanf() function
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0 , j = 0;
char buf[128] = {0};
float numbers[5] = {0.0};
float keep = 0.0;
printf("Please input 5 numbers : \n");
for (i = 0; i < 5; i++)
{
scanf("%f", &numbers[i]);
printf("number %i is %f \n",i,numbers[i]);
}
printf("Done!");
return 0;
}
scanf("%f\n", &numbers[i]); should be scanf("%f", &numbers[i]);

srand() in dice game [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 8 years ago.
I've been searching the site for possible answers to this problem, and although they're all similar they don't seem to be the exact same problem that I have, which is why I've been forced to open this question. SO I need to make a dice game that is supposed to roll 2 dice ranged from 1-6 and the user is supposed to guess what the number will be. The program then outputs the values of the die and reroll's if the guessed value isn't the real value of the 2 die. If it is then the program stops rolling the die and tells you how many rolls it took for the die to reach your guessed value.
For some reason my program keeps rolling the die over and over without stopping and I'm not exactly sure why. I tried testing it in a seperate program and have gotten even more confused as to why I still can't get different values even with srand() being called only once at the beginning of main.(I realized that, among a few other problems were what was wrong with the functions throwCalc1 and the unnecessary throwCalc2) If I try to place rand() outside a variable, I get different values, but if I put it within a variable the values stay the same. I've tried making the variable a function and it still doesn't work as the compiler gives me an error saying "initialization makes pointer from integer without a cast"
test function:
int main(void)
{
srand(time(NULL));
int i;
int *throwCalc = rand() % 6 + 1;
for(i = 0; i < 6; i++) {
printf("value is: %d\n", *throwCalc);
}
return 0;
}
original program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#define MIN 2
#define MAX 12
int getInt(int min, int max) {
int retry = 1;
int value;
char after;
int cc;
do {
printf("Enter total sought \n"
"Range must be within [%d - %d]", min, max);
cc = scanf("%d%c", &value, &after);
if(cc == 0) {
printf("bad char or 0 input, please re-enter input");
clear();
} else if (after != '\n') {
printf("Error:Trailing characters, please re-ente input");
clear();
} else if (value < min || value > max) {
printf("Error: value outside of range, please re-enter input");
clear();
} else {
retry = 0;
}
} while(retry == 1);
return value;
}
void clear() {
while (getchar() != '\n') {
; //intentional empty statement
}
}
int throwCalc1() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwCalc2() {
int a = 1, b = 6, n;
srand(time(NULL));
n = a + rand() % (b + 1 - a);
return n;
}
int throwResult(int input, int getcalc1, int getcalc2) {
int i = 0;
do {
throwCalc1();
throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
printf("You got your total in %d throws!\n", i);
return 0;
}
int main(void)
{
int input = getInt(MIN, MAX);
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
printf("Game of Dice\n");
printf("============\n");
printf("hi number is: %d", input);
throwResult(input, getCalc1, getCalc2);
return 0;
}
You do this once at the top of main:
int getCalc1 = throwCalc1();
int getCalc2 = throwCalc2();
And then expect the values to update just by calling throwCalc1() & 2 again.
Besides fixing srand(), have throwCalc1 & 2 return values into local variables instead of passing something in.
Right now you are calling throwCalc1() and throwCalc2() within your loop, but throwing away the results. You need to save those results in a pair of variables:
do {
getcalc1 = throwCalc1();
getcalc2 = throwCalc2();
printf("Result of throw %d : %d + %d", i, getcalc1, getcalc2);
i++;
} while(input != getcalc1 + getcalc2);
After you've done this, you might notice that getcalc and getcalc2 don't need to be parameters to that function - they can just be local variables within throwResult().
In addition, your throwCalc1() and throwCalc2() functions are identical, so you can remove one them and just call the remaining one twice.
Your test function should look like:
int main(void)
{
srand(time(NULL));
int i;
int throwCalc;
for(i = 0; i < 6; i++) {
throwCalc = rand() % 6 + 1;
printf("value is: %d\n", throwCalc);
}
return 0;
}

Resources