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;
}
Related
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;
}
My code:
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
printf("%d %s ", (int)pow(10, power) - 1, power == n ? "=" : "+");
sum += (int)pow(10, power) - 1;
}
printf ("%d", sum);
return 0;
}
Output in Vs Code with gcc:
Enter a number: 5
9 + 98 + 999 + 9998 + 99999 = 111103
Output in online compilers:
Enter a number: 5
9 + 99 + 999 + 9999 + 99999 = 111105
My question: Why? is this happening?
Possibly an issue with pow and its implementation, perhaps due to different platform or compilers.
Instead of using pow which relies on floating point arithmetic and leads to compounding rounding errors (and possibly contains bugs), why not use simple multiplication? If you start the loop with 10, then you could multiply that by 10 each iteration to get the result you want.
Perhaps something like this:
unsigned sum = 0;
for (unsigned power = 0, value = 10; power < n; ++power, value *= 10)
{
sum += value - 1;
}
[Printing left out]
I just use the function "round" which returns the integer rounding closest to the value specified in parameter
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum=0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
sum += (int)round (pow(10, power)) - 1;
}
printf ("%d", sum);
return 0;
}
At my university I was asked to create a program that asks the user for two inputs. One is the base and the other is the power of a number. I am not allowed to use math.h only loops.
This is my code thus far:
#include <stdio.h>
int main() {
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
for(reps = base; reps <= power; reps += 1) {
printf("* %d ", base);
}
for(number; number <= power;number += 1) {
int result = base * base;
for (result; number <= power; result = base * result) {
result = result * base;
printf("\n or %d", result);
}
}
return 0;
}
Please help me. I am so lost and I feel like crying :( not that it matters.
(Your main issue is that you are using an uninitialised variable; the behaviour of doing that in C is undefined.)
But let's rework the answer. The first thing to do is to separate the actual power function from all the input and output. With regards to that function, I'll put my favourite way into the answer pool on the understanding that you'll work through it carefully and understand it.
You can ace this problem using a technique called exponentiation by squaring:
int getPower(int base, int power/*must be non-negative*/)
{
int ret = 1;
while (power){
if (power & 1){ /*this means the current value of `power` is odd*/
ret *= base;
}
power >>= 1; /*ToDo - figure this out with your debugger*/
base *= base;
}
return ret;
}
The method is adequately explained in https://en.wikipedia.org/wiki/Exponentiation_by_squaring
The loop for calculating the power looks like this
int product = 1;
for(int multiplicationCounter = 1;multiplicationCounter <= power; multiplicationCounter ++) {
product *= base;
}
printf("Result is %d", product);
You can integrate this in your code, maybe change the output.
This should replace your whole second for-loop.
assume both base and power is positive integer,
then
int Result =1;
for (int i=0; i<=power;i++)
{
if(power==0)
Result=1;
Result =Result*base;
}
This should work
#include <stdio.h>
int main()
{
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
int result=1:
for(number=1; number <= power;number += 1)
{
result=result*base
}
printf("The result is %d", result);
return 0;
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}
This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);