There was a question that I needed to find the inverse of the matrix (actually it's about cryptography, but never mind) and to be honest the code works. Nevertheless, if you insert certain numbers into the matrix, the program just fail in to calculate it. Let me show you the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, Mtx_P[4], temp;
float D, Mtx_I[4];
printf("\nInsert the values in a matrix 2x2: "); // Insert the values
for(i=0;i<4;i++)
{
scanf("%d", &Mtx_P[i]);
}
printf(" \n");
for(i=0;i<4;i++) // Print the values
{
printf("%d\t", Mtx_P[i]);
if(i == 1)
{
printf("\n\n");
}
}
D = (Mtx_P[0] * Mtx_P[3]) - (Mtx_P[1] * Mtx_P[2]); // Find and print the determinant
printf("\n\n-------------------------\n\nDeterminant = %f\n", D);
float Mtx_Pf[4];
//double Mtx_Pf[4]; I've tried with double to see if worked
for(i=0;i<4;i++) // Find the inverse...
{
Mtx_Pf[i] = Mtx_P[i];
}
Mtx_I[0] = Mtx_Pf[0]/D; // ...divind the values by the determinat
Mtx_I[1] = Mtx_Pf[1]/D;
Mtx_I[2] = Mtx_Pf[2]/D;
Mtx_I[3] = Mtx_Pf[3]/D;
temp = Mtx_I[0]; // swaping the places of the first number with the lastest one
Mtx_I[0] = Mtx_I[3];
Mtx_I[3] = temp;
Mtx_I[1]*=-1; // the secondary diagonal get negative
Mtx_I[2]*=-1;
printf("\n-------------------------\n\nThe invertible Matrix:\n\n ");
for(i=0;i<4;i++) // Print the inverse
{
printf("%f\t", Mtx_I[i]);
if(i == 1)
{
printf("\n\n");
}
}
double test = 1/(-26);
printf("\n\n-------------------------\n(Test: %lf)\n\n", test); // Testing to see if it can't calculate
return 0;
}
My problem happens when I try to divide the element by the determinant using this matrix:
1 10
3 4
When is the time to calculate 1 by -26 (determinant) it prints 0,0000, but actually 1/(-26) is −0,038461538 (according to the calculator).
You probaly already realize that this trouble doesn't have any relation with matrixes, but somebody knows how to fix this error?
The issue is that your temp variable (used for swapping) is an int and assigning a float to an int truncates the value. Define it as a float or double instead.
float D, Mtx_I[4], temp;
In addition, note that 1/(-26) is integer division, resulting in truncation. To perform floating-point division, one of the operands must be a floating-point value (e.g. 1./-26).
#include <stdio.h>
double calculate_average (int number)
{
static int numberInput = 0; //counter
static int sum = 0;
sum = sum + numberInput;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average;
while (1)
{
int number;
scanf("%d", &number);
if (number == 0)
break; //stops if number == 0
else
average = calculate_average(number);
}
printf("%.1f\n", average);
return 0;
}
As I can personally tell, the function is trying to calculate the average. But why does the main function not use the number in the calculate_average function?
As written, your calculate_average function does not use its given number argument because, nowhere in that function, do you instruct it to do so. Most likely, your sum = sum + numberInput; should really be sum = sum + number; (thus adding that given number to the running total).
A couple of other points:
You should initialize your average variable (to 0.0), otherwise you'll get a crazy result if you give your program an empty list (i.e. give zero as the first entry).
As your function returns a double, it is best to have the sum variable also as a double; otherwise, you are performing integer arithmtic in your calculation, and all returned values will be truncated to integers (losing any fractional parts).
Others will likely point out that you should always check the value returned by your scanf call (it will be 1 if the read operation succeeds) and add code to handle any error; however, addressing that point here is, IMHO, beyond the 'remit' of this question, but see this answer to How validate user input when the expected value is of type int and the entered value is not of type int?.
Here's a possible working version:
#include <stdio.h>
double calculate_average(int number)
{
static int numberInput = 0; //counter
static double sum = 0.0;
sum = sum + number;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average = 0.0; // Always best to initialize variables!
while (1) {
int getal;
scanf("%d", &getal);
if (getal == 0)
break; //stops if getal == 0
else
average = calculate_average(getal);
}
printf("%.1f\n", average);
return 0;
}
Please feel free to ask for any further explanation and/or clarification.
I was assigned a Hw that required me to calculate the value of e via using the series:
1 + 1/1! + 1/2! + ...1/n!
The value of e must be calculated until the value of n (entered by the user) is reached. Also, the value of 1/n! must be calculated until it's value is smaller than epsilon (also entered by the user).
I wrote the code, but there are some errors that compiler is telling me errors such as relational comparisons, use of ';' etc. Could anyone please help me fix the error. Thank you in advance.
Below is my code:
#include<stdio.h>
int factorial (int i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void) {
int i,n;
float e,ep;
printf("what is the value of epsilon: ");
scanf("%f",&ep);
printf("what is the value of n: ");
scanf("%d",&n);
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
for(1/fatorial(i)<=ep)
printf("The value of e for the entered value of epsilon and n:%f",e);
return 0;
}
For more precision I would use double instead of float.
for (i=1; i<=n, i++)
e= 1+1/factorial(i);
This is wrong, you are not adding to e, you are assigning always the last
value of the series, which is always 0 (except for i = 1). So your e will
always be 1.
factorial is a function that returns an int. A int divided by an int is
an int and in C anything 1/x (for x > 1, x integer) is 0. You you to use
1.0 or cast at least one of the arguments to double (or float if you are
using floats):
double e = 1; // initializing e
for(i = 1; i <= n; ++i)
e += 1.0/factorial(i);
Also, the value of 1/n! must be calculated until it's value is smaller than epsilon, also entered by the user.
I don't understand what that means, if n is a fixed value given by the user,
what do you keep calculating? Is this really what the exercise says?
My interpretation would be: if by n steps |e_real - e_calculated| > epsilon,
keep incrementing n, otherwise stop. That would be
#include <stdio.h>
#include <math.h>
#include <stdint.h>
uint64_t factorial (uint64_t i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}
int main(void)
{
int n;
double e = 1;
double epsilon;
printf("what is the value of epsilon: ");
scanf("%lf", &epsilon);
printf("what is the value of n: ");
scanf("%d",&n);
int i = 1;
while(1)
{
e += 1.0/factorial(i++);
if(i >= n && (fabs(e - M_E) < epsilon))
break;
}
printf("e: %.20lf, calculated e: %.20lf, error: %.20lf, steps: %d\n", M_E, e, fabs(e-M_E), i);
return 0;
}
Note: if you are using GCC, you have to compile it with the -lm option:
$ gcc e.c -oe -lm
You're not summing the series but actually set e to 1.
Because you set it to e + 1/factorial(n) but your factorial() returns an int which is very likely to be above 1, so the division is integral, and 1 divided by any greater number will give 0.
The last loop is very strange. Did you mean while rather than for? Note that factorial is mistyped. Moreover, no work is done in the loop's body other than printing the same message over and over.
I have to write a program that takes in two positive integers, start and end, where (1 < start < end). Then the program would look within this range [start, end] and count the number of powers of 3.
So, for example, if start is 2 and end is 10, the output would be 2. (as 3 and 9 are powers of 3).
Below is my code:
#include <stdio.h>
#include <math.h>
int main(void) {
int start, end, i, count = 0;
printf("Enter start and end: ");
scanf("%d %d", &start, &end);
for (i = start; i <= end; i++) {
if ((log(i) / log(3)) == floor((log(i) / log(3)))) {
printf("%d\n", i);
count++;
}
}
printf("Answer = %d\n", count);
return 0;
}
But, when I tried to run one of the test cases [3, 1000], the output is 5, when it should be 6.
3
9
27
81
729
Answer = 5
The number 243 is missing. Is there something wrong with my code?
The problem is you are using exact comparison of floating point numbers. Specifically, here:
if ((log(i)/log(3)) == floor((log(i)/log(3))))
Since log() and floor() return double, you're comparing without any tolerance two values which cannot be compared that way.
How should I do floating point comparison?
Your immediate problem has to do with the imprecision of floating point numbers, something that is generally well documented on the net, including various methods useful in fixing that problem.
However, I'm not actually going to bother referring you to them because the use of floating point is totally unnecessary here. There's a much more efficient way of doing this that involves only integers.
Rather than going through numbers in your range looking for powers of three using floating point operations, you would be better off going through powers of three (using just integer multiplication) looking for numbers in your range.
In pseudo-code, that would go something like:
powerOfThree = 1
while powerOfThree <= endRange:
if powerOfThree >= startRange:
print powerOfThree
powerOfThree = powerOfThree * 3
You could even make it more efficient by selecting a more suitable starting value for powerOfThree but, since there are only 40-odd powers of three in a 64 bit number, that's probably a waste of time.
When converting from pseudo-code to the more concrete C, you unfortunately come across the limitations of the datatypes in that language, specifically the fact that multiplication may result in overflow.
There are various ways you can avoid this this such as detecting that it's about to happen and exiting the loop early.
Given below is the function that you need, one which handles this issue, along with some test code which can be used for validating it.
#include <stdio.h>
#include <limits.h>
// I hate typing :-)
typedef unsigned long ULONG;
typedef unsigned int UINT;
static UINT countPowersOfThreeBetween (ULONG low, ULONG high) {
// Catch invalid params, just exit with zero.
if (low > high) return 0;
// Go through all powers of three.
ULONG powerOfThree = 1;
UINT count = 0;
do {
// If within your range, count it.
if ((powerOfThree >= low) && (powerOfThree <= high)) {
count++;
// printf ("DEBUG: got %lu\n", powerOfThree);
}
// Early exit if about to overflow.
if (ULONG_MAX / powerOfThree < 3) break;
// Advance to next power and continue if within range.
powerOfThree *= 3;
} while (powerOfThree <= high);
// Notify caller of count.
return count;
}
// Test function to make test suite easier.
static void testRange (ULONG low, ULONG high) {
UINT count = countPowersOfThreeBetween (low, high);
printf ("In range %lu..%lu, found %u occurrences\n", low, high, count);
}
// Test suite, add whatever you need.
int main (void) {
testRange (1000, 10);
testRange (0, 0);
testRange (9, 9);
testRange (3, 1000);
testRange (0, ULONG_MAX);
testRange (ULONG_MAX, ULONG_MAX);
return 0;
}
As you will see from the output, this gives the correct counts for various ranges:
In range 1000..10, found 0 occurrences
In range 0..0, found 0 occurrences
In range 9..9, found 1 occurrences
In range 3..1000, found 6 occurrences
In range 0..18446744073709551615, found 41 occurrences
In range 18446744073709551615..18446744073709551615, found 0 occurrences
And, if you uncomment the printf line in countPowersOfThreeBetween(), you'll also see the actual values detected.
Before choosing floating point types in the future, I strongly recommend you read this article entitled "What every computer scientist should know about floating-point arithmetic", by David Goldberg. It explains your problem(s) nicely, much better than I could have.
You don't actually need floating point (or negative integer) types here, so they should be avoided. Form your powers by multiplication, rather than addition:
#include <assert.h>
#include <limits.h>
#include <stdio.h>
int main(void){
unsigned int start, end, i, count = 0;
printf("Enter start and end: ");
int x = scanf("%u %u", &start, &end);
assert(x == 2); // XXX: INSERT PROPER ERROR HANDLING!
// find the first power greater than or equal to start
for (i = 1; i < start && UINT_MAX / 3 >= i; i *= 3);
// ... then count each one less than or equal to end
while (i <= end && UINT_MAX / 3 >= i) {
printf("%u\n", i);
i *= 3;
count++;
}
printf("Answer = %u\n", count);
}
Your problem is round-off error while float calculating in computer, the result of log(243)/log(3) is not exactly log3(243), where computer store approximate value of it. eg, in my 32bit computer, it is 4.99999999999999911182.
However, you have two ways to solve it,
use integer calculation instead of float.
simple mathematical transformation.
number of powers of 3 in [start, end] is equivalent to floor(log3(end)-log3(start))+1, wrote in c is
printf("answer:%d\n", (int)((log(1000)-log(3))/log(3))+1);
complete code:
#include <stdio.h>
#include <math.h>
int pow3(int n) {
int ret = 1;
while(n--) {
ret *= 3;
}
return ret;
}
int main() {
int a, start, end, answer;
scanf("%d%d", &start, &end);
a = (int)(log(start+0.5)/log(3));
//printf("%d,%d,%d\n", a, pow3(a), start);
if(start == end) answer = (start == pow3(a));
else answer = (int)((log(end+0.5)-log(start))/log(3))+1;
printf("answer = %d\n", answer);
}
Result:
Input[0]: 2 10
Output[0]: 2
Input[1]: 1 3
Output[1]: 2
Input[2]: 3 1000
Output[2]:6
Your program fails because of floating point precision issues.
Use integer arithmetics instead:
#include <limits.h>
#include <stdio.h>
int main(void) {
unsigned int start, end, i, count;
printf("Enter start and end: ");
if (scanf("%u %u", &start, &end) == 2) {
for (i = 1, count = 0; i <= end && i <= UINT_MAX / 3; i *= 3) {
if (i >= start) {
printf("%u\n", i);
count++;
}
}
printf("Answer = %u\n", count);
}
return 0;
}
A direct solution with floating point arithmetics is possible too:
#include <math.h>
#include <stdio.h>
int main(void) {
unsigned int start, end, count = 0;
printf("Enter start and end: ");
if (scanf("%u %u", &start, &end) == 2) {
if (end > 0 && end >= start) {
int start3 = (start <= 1) ? 0 : (int)(log(start - 0.5) / log(3));
int end3 = (int)(log(end + 0.5) / log(3));
count = end3 - start3;
}
printf("Answer = %u\n", count);
}
return 0;
}
I have another problem for homework. This time I know where I am at generally, but I can see that I have some glaring issues with the code. Recently I lost my keys, and it's kind of like that. I don't know exactly WHERE I went wrong with my code, but I have a good idea, and I'd like you to help me find it.
The problem is to approximate pi using the Taylor series.
Now, my problem isn't exactly to get it to approxate so that it equals pi. Rather approximate pi using first N terms as entered by the user. So for example, if I would enter 2, then I should run through the first 2 since N=2. My problem is the way printF represents it (and a variable appears to be uninitialized). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms;
int sign= 1;
int n;
float sum= 0.0;
float next_Term;
float final_sum;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&n);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
sum= sum+next_Term;
next_Term = sign*(1.0/(2*n-1));
sign = sign*-1;
}
final_sum = sum*4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}
I don't know exactly WHERE I went wrong with my code
Firstly you are scanning value into a variable n and then later using it as an iterator variable. Change this to be num_Terms. This should solve your main problem of not considering the number of terms.
Then, it is preferable to initialize the variable before you use it, which would then get rid of the warning you get.
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms = 0;
int sign = 1;
int n = 0;
float sum = 0;
float next_Term = 0;
float final_sum = 0;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&num_Terms);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
//not too sure if you need to reverse this order of calculation of sum
sum = sum + next_Term;
next_Term = sign * (1.0/(2*n-1));
sign = sign * -1;
}
final_sum = sum * 4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}