Subtracting two time interval - c

I wanted to subtract two time interval. here one time interval is 5hour 30 minute and other is current time.the code is written as follow.
main()
{
int Time1;
int Time2;
int hour=10;
int minute=5;
int second=13;
int h; int m;
int Ntime;
Time1=(60*5)+(30);
Time2=60*hour+minute;
Ntime=Time2-Time1;
m=(Ntime%60);
Ntime=Ntime/60;
h=(int)(Ntime);
printf("hour after subtraction is : %d hour %d min",h,m)
}

I have not looked at any logical errors in your program but the error you post is due to the fact that the mod operator i.e. % expects the operand to be integer. So if you modify your code in this way, it should remove the error.
main()
{
int Time1;
int Time2;
int hour=10;
int minute=5;
int second=13;
int h; int m;
int Ntime; //double has been changed to int
double Ntime2;
Time1=(3600*5)+(60*30);
Time2=(3600*hour)+(60*minute)+second;
Ntime=Time2-Time1;
Ntime2=((double)((Ntime%60)/100) + (double)(Ntime/60));
h=(int)(Ntime2);
m=((Ntime2 - (double)h)*100);
printf("hour after subtraction is : %d hour %d min",h,m)
}
There is too much type casting involved in your code, you should look for a simpler way to do this. Look into the time.h header file, you may find something useful to work with.

The % operator is meant for integer values only. It won't work with a double variable.
Change your code to:
Ntime = (((int)Ntime%60) / 100 + (Ntime / 60));

change your statement of calculating Ntime to,
Ntime=((float)((int)Ntime%60)/100+(Ntime/60));
you need to type cast to float/double otherwise /100 will result in integer so fractional part will be truncated.

Related

sum of positive integer returning negative number - C

Beginner in C language.
I suspect it may be due to overflow, but could not solve this simple exercise:
program to compute the sum of squares of all the natural numbers smaller than 10000
I initially tried:
#include <stdio.h>
int main() {
int a = 10000;
int square(int num) {
return num * num;
};
int total = 0;
while (a > 0) {
a--;
total += square(a);
//printf("a is %d and square is %d and total %d \n", a, square(a), total );
};
printf("total is %d ", total );
return total;
}
result: total is -1724114088
and here there's the strange thing:
...
a is 9936 and square is 98724096 and total 2063522144
a is 9935 and square is 98704225 and total -2132740927
...
So I tried to change total to long, tried to change declaring square function as long square(int num ), but nothing changed.
Could you explain why the sum turns negative ?
Is it due to overflow ? But why not resetting to 0 or positive, instead of going negative ?
how can I know how many bits for int are there in a computer that I don't know (e.g. cloud ?
E.g. I am coding here: [https://www.programiz.com/c-programming/online-compiler/]
Which is best practice to fix it ?
Do not define function in functions.
int main() {
int square() { // NO!
Functions belong at file scope:
int square() { //OK
}
int main() { //OK
}
The code compiles because compilers have extensions to the language. It's not part of the C programming language.
Could you explain why the sum turns negative ?
See ex. why the value of sum is coming out to be negative? and other questions. The sum "wraps around" on your platform.
Is it due to overflow ?
Yes.
But why not resetting to 0 or positive, instead of going negative ?
Because systems nowadays are twos-complement, it's simpler to implement a single hardware instruction for adding numbers then two separate instructions with special overflow semantics. Unsigned and signed twos-complement numbers behave the same when doing operations on them, so instead of doing special semantics on overflow, when adding signed numbers they are added the same as they would be unsigned (bits are just added) and the result is then interpreted as a signed number (in a C program), which because the most significant bit becomes set the number becomes negative.
Anyway, compiler just does not care, because signed overflow is undefined behavior compiler does not have to care. The compiler just generates a hardware instruction for signed addition, which behaves as explained above.
how can I know how many bits for int are there in a computer that I don't know
You can check your compiler documentation.
But usually it's simpler to just compile a simple C program where you use CHAR_BIT - the number of bits in a byte - and sizeof(int) - the number of bytes in an int - and inspect the output of that program. For example, a program such as:
#include <stdio.h>
#include <limits.h>
int main() {
printf("There are %d bits in int\n", (int)sizeof(int) * CHAR_BIT);
}
Note that number of bits in types does not only change with platform and operating systems, it can change with compiler, compiler versions and also compilation options.
Which is best practice to fix it ?
This depends on what behavior do you want.
To calculate bigger values use a bigger datatype - long or long long. When the language features are not enough, move your program to use some big number library.
If you want to terminate the program in case of problems - you can check for overflow and call abort() or similar if it happens.
Instead, you could have used a formula.
Sum of Squares of first N natural numbers = (N * (N + 1) * (2 * N + 1) / 6
For now, let N be 10000.
Ignoring the 6 in the formula, the sum of squares is as big as 10^12. It will not fit in an integer. You should use a data type that can accommodate bigger values, like long or long long int.
Here's the modified code.
#include <stdio.h>
int main() {
int a = 10000;
int square(int num) {
return num * num;
};
// Change int to long long int
long long int total = 0;
while (a > 0) {
a--;
total += square(a);
//printf("a is %d and square is %d and total %d \n", a, square(a), total );
};
// Change %d to %lld
printf("total is %lld ", total );
return total;
}
You'll need to change all uses of int to long:
#include <stdio.h>
int main() {
long a = 10000;
long square(long num) {
return num * num;
};
long total = 0;
while (a > 0) {
a--;
total += square(a);
//printf("a is %ld and square is %ld and total %ld \n", a, square(a), total );
};
printf("total is %ld ", total );
return 0;
}
which prints total is 333283335000
EDIT
Or you could just change the total, the return type of square, and perform the appropriate casts when computing the squared values:
#include <stdio.h>
int main() {
int a = 10000;
long square(int num) {
return (long)num * (long)num;
};
long total = 0;
while (a > 0) {
a--;
total += square(a);
//printf("a is %ld and square is %ld and total %ld \n", a, square(a), total );
};
printf("total is %ld ", total );
return 0;
}
Produces the same result shown above.
onlinegdb here

range of long int, long long int and int

I have to print product of elements of array A mod 10^9+7,there should N elements in array and the constraints are 1<=N<=10^3 and 1<=A[i]<=10^3.
The code I wrote
#include<stdio.h>
int main()
{
int N, pro = 1;
scanf("%i", &N);
int arr[N];
for (int i = 0; i<N; i++) {
scanf("%i", &arr[i]);
pro = (pro*arr[i]) % (1000000007);
}
printf("%i", pro);
}
gave wrong answer but when I replaced int arr[N] to long int arr[N] and changed its precision specifier to %li it gave correct output.
My confusion is when the upper limit of array's elements is only 10^3 then why using long int worked and not just int.
i am using 64 bit windows OS and the inputs which i am giving are 3 digit numbers
as array elements for example 568,253 etc without any 0 in beginning.
Consider the case where N = 3 and A = [10^3,10^3,10^3].
After the second iteration, your product will be 10^9.
In the third iteration, your product will be (10^9 * 10^3) % 1000000007.
Before doing the modulo operation, the product would create integer overflow and hence the WA.
The problem may be the result of the expression (pro*arr[i]).
If we assume that the maximum value of pro is 1000000006 due to the modulo, and the maximum value of arr[i] is 10^3 as mentioned. So, this expression may take a value greater than a 32bit integer.
The other thing to look for is What the type of (pro * arr[i]) ? :
The compiler answers this question by look to the operands of the expression, and will set the return type, for integer, as the greater type of them.
If you set arr[] as an long int [] this expression will return a long integer, whereas, if you set arr[] as an int, it will return an int and so it'll be wrong :
int * int -> int
int * long int -> long int

Double variable doesn't return the right values of a division [duplicate]

This question already has answers here:
Why dividing two integers doesn't get a float? [duplicate]
(7 answers)
Closed 5 years ago.
input example : 356
356/100, is suppused to be 3.56
But I'm getting 3.0000000000, I'm using ideone online compiler for C.
#include <stdio.h>
#include <math.h>
int main() {
int n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}
That's because here frac = (n/100); you are doing plain integer arithmetic (as n is declared as an int and 100 is interpreted as an int (any whole number is taken to be an int unless specified otherwise)). What you need to do is say explicitly that you want to do an arithmetic operation with digits after decimal point. One way is to use a cast: frac = ((double) n/100);
If you don't use the cast, the division will be performed as you expect, but then the digits after the decimal point will be dropped. Since frac is declared as a double, 0s would get tacked on to the end.
In C, the result of division of two integer numbers (e.g. int, short, long) is also an integer (it is counter-intuitive, but it is implemented this way for performance reasons). As a result, the result of 5/2 is 2 and not 2.5. This rule is only for integer numbers. So, if you need to get a floating-point result, at least one of the numbers in a division operation must be of a floating-point type.
In case of your code, if you use 100.0 instead of 100, you will get the desired result. Also you can use casts or define n as double.
This should work:
#include <stdio.h>
#include <math.h>
int main() {
int n; // You can define n as double but don't forget to modify scanf accordingly.
double frac;
scanf("%d", &n);
frac = (n/((double)100)); // Or, frac = (n/100.0)
printf("%lf", frac);
return 0;
}
You cannot call division using integers to be double without declaring it.
For example
int / int will result int.
Try declaring n as double
double n;
scanf("%lf", &n);
frag = n/100;
input data type is an integer.
just change it to double or float to fix this problem.
int main() {
double n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}

To print the answer from the series -> x^3 - x^5 + x^7 - x^9 +

#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
float sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=1;i<=n;i++)
{
sum+=(pow(x,2*i+1) * pow(-1,i+1));
}
printf("%f",sum);
return 0;
}
I'm trying to solve this series in C language. Am I doing something wrong in the above code?
Yes, you're a bit wrong. In your code
printf("%f",sum);
sum is an int and using %f to print the value of an int is undefined behaviour.
The function pow() returns a double. You may want to change your sum to type double.
If you don't mind using your own version, a better looking implementation, without using pow() will be
Store the existing value.
Multiply by x * x on each iteration
Take care of -ve sign for even numbered iteration.
First things first, your printf has the wrong format specifier for an int: use %d instead. But for non-integral x, you'll want to refactor to a double anyway, so %f will probably be retained.
Secondly, don't use pow: it will not be precise (probably implemented as exp(log)) and you don't need to evaluate the power from scratch for each term.
Keep a running power: i.e. compute x * x * x initially, then successively multiply that by x * x for subsequent terms. Don't forget to alternate the signs: you can do that by multiplying by -1.
you are trying to find x^3,x^5 that is power in odd. so do a little change in your for loop. write this instead of your code. and if you give a large x or n value then it is preferable to declare sum as a long data type
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
long sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=2;i<=n;i+=2)
{
sum+=(pow(x,i+1) * pow(-1,i));
}
printf("%l",sum);
return 0;
}
First of all, you are trying to evaluate a series that diverges for all points outside and on the circle of radius one (as a complex series). If you use an int for x, you will get each time values bigger and bigger, oscillating around 0. Try it with numbers of ||x|| < 1 (this means double or float for x)
All the other answers posted are also usefull to get sooner to the expected value.

C weird approximation on floating point [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 8 years ago.
I have the following code:
#include<stdio.h>
int main(int argc, char const *argv[])
{
float min, max, step;
min = -0.85, max = 0.85, step = 0.002;
int rank = 3, total = 4;
float step1 = min + (max - min) * rank / total; // should be 0.425
printf("%f %.7g\n", step1, step1); // 0.425000 0.4250001
float step2 = min + (max - min) * (rank + 1) / total - step; //should be 0.848
printf("%f %.7g\n", step2, step2); // 0.848000 0.848
float noc = (step2 - step1 + step) / step; //should be 212,5
printf("%f %.7g\n", noc, noc); // 212.499985 212.5
int nol = 1200;
int result = (int)nol * noc; //should be 255000
printf("%d\n", result); // 254999
return 0;
}
This is a fragment of code isolated from a project I have to do. The final result should be 255000, but for some causes, it shows 254999. Can someone please explain me what happens in the process? I have read somewhere that multiplying a floating number with 10^k and then dividing back solves such problems, but in this case, due to the variable step varying from 0.000001 to 0.1, I can't actually use that (in the same way, I can't use a defined EPSILON). What else can I do?
Thanks in advance!
P.S.: I have used double and long double as well, but with same problems, only this time error propagates from a further decimal. I am using gcc 4.8.2, under Ubuntu 14.04.1.
Truncation vs. rounding.
Due to subtle rounding effect of FP arithmetic, the product nol * noc may be slightly less than an integer value. Conversion to int results in fractional truncation. Suggest rounding before conversion to int.
#include <math.h>
int result = (int) roundf(nol * noc);
the significant problem(s) are:
1) mixing floating point and double with integer math
--so the compiler promotes all the math to float (or double)
2) not all numbers can be expressed exactly in float
3) --the initialization of min, max, step are taking double literals
and converting them to float
--even double cannot express all values exactly
--some precision is lost when performing the conversion from double to float
4) this code excerpt: (rank + 1) / total is always = 1
--(although the many conversions may result in being 'not exactly' 1)
5) argc and argv are not referenced in your code.
--this, given that all warnings are enabled, will rise two warnings
at compile time about unused parameters
6) this line in your code is not correct syntax
--(although the compiler might not complain) #include<stdio.h>
--it should be #include <stdio.h>
--sometimes spaces count, sometimes they dont

Resources