I've created a program which takes an integer x input, then loops until x is met while also taking other integer inputs. I then do various calculations, and then find a square root of a certain value. When I divide by square root however I get a 0 when I know I should be getting a different value as the maths doesn't add up.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void) {
int multiply1, multiply2, add, squareRoot;
int i;
int n;
int x;
int s;
double divide, test = 0;
scanf("%d", &x);
for (s = 0; s < x; s++) {
scanf("%d %d", &i ,&n);
}
multiply1 = i * i;
multiply2 = n * n;
add = multiply1 + multiply2;
squareRoot = sqrt(add);
printf("%d", i);
test = (i / squareRoot);
printf("Multiplication = %d\n", multiply1);
printf("Multiplication = %d\n", multiply2);
printf("Added together = %d\n", add);
printf("square root = %d\n", squareRoot);
printf("First output = %.3f\n", test);
return 0;
}
You are dividing two integers so the actual division returns the result rounded down. You should instead cast to double and then divide.
test = ((double)i/squareRoot);
There are two things you can do,
Without changing your program, simply cast the i and squareRoot variables to double
test = (double) i / (double) squareRoot;
Change your program and make i and squareRoot a double.
I, would choose 2 because sqrt() returns a double and that might cause an integer overflow.
Related
I want to turn a number like 0.1235 to 1235.
i tried to do it through a loop by multiplying by 10 but i didnt know how to stop the loop.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main (){
double a;
printf("a:");
scanf("%lf", &a);
while (/* condition */)
{
a = a*10;
}
printf("a: %lf",a)
getch ();
return 0;
}
int var = (int)round(0.1235 * 10000);
This is not an easy problem to solve as it may seem at first due to decimal precision and lack of implementation details in your question. Here is an attempt of a solution to your problem, but you might need to adjust it depending on your needs.
#include <stdio.h>
#include <math.h>
#define DELTA 0.00001
int get_number_of_decimal_places(double num)
{
int count = 0;
do {
num = num * 10;
++count;
} while (num - (int)num > DELTA);
return count;
}
int main()
{
double a;
int result = 0;
printf("a:");
scanf("%lf", &a);
int decimal_places = get_number_of_decimal_places(a);
do {
a *= 10;
result += (int)a * pow(10, --decimal_places);
a -= (int)a;
} while (decimal_places != 0);
printf("result: %d", result);
getch();
return 0;
}
For input value 0.12345, the output is:
12345
Keep in mind that this solution treats input values 0.1, 0.0001, 0.010 etc. the same way, so the output would be:
1
I am trying to pass a number an found its root
I tried running this code to an online compiler and I get random numbers that I didn't entered with scanf. I tried it on an online compiler that can be found here https://www.onlinegdb.com/online_c_compiler#.
For some reason whatever I put I get 8. I also tried it in DEV-C++ which can found here https://sourceforge.net/projects/orwelldevcpp/ in that complier I always get 0 instead of my input number. There is also printf for confirmation to scanf and seems to me that the value actually becomes my input but when I call the function everything changes any ideas (thanks for ur time)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define g(x,num) 1.0/3.0*(2.0 * x + (num / x)) //f'(x,num)
#define var 1E-10//10^-10
#define f(x,num) x*x - num
double x;
int i;
double num;
void sqrtNR(double num){// **actual bug**
printf ("\nnum: %d\n", num);
x = num;
printf ("x: %d\n", x);
for(i;var < fabs(f(x,num)) ; i++) { **infinite loop**
x = x - ( f(x,num)/g(x,num) );
// printf ("x: %d\n", x);
}
printf ("metrhths %d\n", i);
return x;
}
int main(int argc, char** argv) {
printf("dwse ari9mo\n");
scanf("%lf", & num);
printf("%lf", num);
sqrtNR(num);
//printf("\nsrtNR : %lf", sqrtNR(num));
}
youknow actually get the for at least working cuz now its on infinite loop
Your printf formats are wrong and cause the UB.
Abstracting from the math logic of your function.
void sqrtNR(double num)
{
printf ("\nnum: %f\n", num);
x = num;
printf ("x: %f\n", x);
while(var < fabs(f(x,num))
{
x = x - ( f(x,num)/g(x,num) );
}
return x;
}
you should also put your macro parameters in the parenthesizes
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void averageGuess(int);
int main()
{
int i, userInput, compGuess, totalGuess, loopGuess = 0;
srand(time(NULL));
printf("Please enter a number between 0 and 99: \n");
scanf("%d", &userInput);
for(i = 0; i < 50; i++)
{
loopGuess = 0;
do
{
compGuess = (rand() % 100);
loopGuess++;
} while(compGuess != userInput);
totalGuess += loopGuess;
}
averageGuess(totalGuess);
return 0;
}//end main
void averageGuess(int totalGuess)
{
float average;
average = totalGuess / 50;
printf("The program took an average of %lf random number generations to match the target number over the 50 experiments.", average);
}//end function
The goal is for the program to print out a float but all I get is integers. I've compiled it in Codeblocks and an Online C compiler but the latter is giving me negative numbers while Codeblocks doesn't return a float.
Can't tell if it is an issue with my code or compiler.
It is an issue with the code here:
average = totalGuess / 50;
The '/' operator sees two integers it has to divide and hence returns an integer. If you need the result to be a float use 50.0 instead of 50
I've compiled it in Codeblocks and an Online C compiler but the latter is giving me negative numbers
this line:
int i, userInput, compGuess, totalGuess, loopGuess = 0;
is not setting all variables to 0, just loopGuess. So totalGuess isn't initialized, which explains
the difference in behaviour (and wrong result, initial value of totalGuess is random, can be negative) between different compilers. Fix:
int i, userInput, compGuess, totalGuess = 0, loopGuess = 0;
The goal is for the program to print out a float but all I get is integers
Then use floating point division, not integer division
float average;
average = totalGuess / 50.0;
gcc doesn't warn about the uninitialized variable (bad!) but clang does (and even suggests the right fix, wow!):
S:\>gcc -Wall -Wextra test.c
(no warnings!!)
S:\>clang -Wall -Wextra test.c
test.c:23:9: warning: variable 'totalGuess' is uninitialized when used here
[-Wuninitialized]
totalGuess += loopGuess;
^~~~~~~~~~
test.c:8:44: note: initialize the variable 'totalGuess' to silence this warning
int i, userInput, compGuess, totalGuess, loopGuess = 0;
^
= 0
There are two issues with the code:
a) totalGuess is divided by integer so the result is rounded to int value
average = totalGuess / 50;
b) negative numbers comes from the fact that
totalGuess variable is not initialized so it can be any number (like big negative to start with).
Corrected program:
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void averageGuess(int totalGuess)
{
float average;
average = totalGuess / 50.0;
printf("The program took an average of %.2f random number generations to match the target number over the 50 experiments.", average);
}
int main()
{
int i, userInput, compGuess;
int totalGuess = 0;
double loopGuess = 0;
srand(time(NULL));
printf("Please enter a number between 0 and 99: \n");
scanf("%d", &userInput);
for(i = 0; i < 50; i++)
{
loopGuess = 0;
do
{
compGuess = (rand() % 100);
loopGuess++;
} while(compGuess != userInput);
totalGuess += loopGuess;
}
averageGuess(totalGuess);
return 0;
}//end main
We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.