Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i have a function that counts arithmetic mean of even numbers in an array.
int func(int *x, int length)
{
float even_sum = 0;
int even_num;
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++;
}
}
result = even_sum/even_num;
return result;
}
giving an array 1 2 2 1 i expect to receive 2 as mean, but i keep getting 0 as result. Where is a mistake in my code?
int func(int *x, int length)
{
float even_sum = 0;
int even_num; // <-- uninitialized, could be anything!
int i;
float result;
for (i = 0; i<length; i++)
{
if (x[i] % 2 == 0)
{
even_sum = even_sum + x[i];
even_num++; // <-- adding 1 to anything yields undefined behavior
}
}
result = even_sum/even_num; // <-- even more undefined behavior
return result;
}
You initialized some, but not all of your variables. It's best to get in the habit of setting your variables to sensible starting values, just as you do here with float even_sum = 0;
Initialize even_num=0
If you don't initialize variables, they can have garbage values.
In your case, even_num has a huge values, greater that even_sum causing your result to be 0.
#Pbd is correct. If you have the latest version of gcc installed and use the command line flags -Wall -Wextra -Wshadow when compiling, it will give you a warning for uninitialized values. 🤓
I think The only problem in your code is when you are passing int array into this function. Apart from that everything looks fine. I ran the code by initialling the 'x' array and it is working fine.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is code written by me where I have to print a single integer denoting the minimum possible capacity of a tram (0 is allowed). It's a problem from codeforces. The answer in CodeBlocks is showing 6 (the right answer) but in codeforces compiler I'm getting another output.
Why is this happening?
#include <stdio.h>
int main() {
int n, i, j, max = 0, sum = 0;
int pssnger_left;
scanf("%d", &n);
int a[n][2];
for (i = 0; i < n; i++) {
for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]); // declaring the value of array
}
}
pssnger_left = a[0][0] + a[0][1];
for (i = 1; i < n; i++) {
sum = pssnger_left - a[i][0];
sum = sum + a[i][i];
pssnger_left = sum;
if (max < sum)
max = sum;
}
printf("%d", max);
}
Input:
4
0 3
2 5
4 2
4 0
Output:
4221555
Answer:
6
Checker Log
wrong answer expected 6, found 4221555
Here is the link of the problem: https://codeforces.com/problemset/problem/116/A
Different compiler, different answer, 99% of the cases is explained by Undefined Behaviour, UB.
In the shown code here it is a[i][i];.
For any i > 1 that is not what you want it to be
and for most high i it illegally accesses beyond a.
-> Undefined Behaviour.
A hint on how I spotted this:
Whenever I see [i][i], actually whenever I see [same][same],
I think "diagonal in a square". And in your code I immediatly thought "What square?", because when seeing int a[n][2]; I thought "Long narrow table." and got a conflict of shapes there.
The problem is not basically with the compiler.
You are doing
sum = sum + a[i][i];
but you have declared a 2D array of n x 2 i.e. int a[n][2]
see in some compilers it shows out of bound because you are accessing an element which is not there in the array
and in compilers it just loops in the already existing array for ex if your array has 5 elements and you are trying to access 6th element then it will go back to 1st index,
so this might be whats happening here.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I been struggling with this piece of code and I can't really figure out what is wrong with it. The code simply takes an input integer k from the user, passes it to the powerOfTen function along with a pointer of type double, and calculates the result. But, when I store the result inside the *my_dbl and try printing that value through *my_double, I get nothing as a result.
#include <stdio.h>
void powerOfTen(int k, double *my_dbl);
int main()
{
int k;
double *my_double;
scanf("%d", &k);
power_of_ten(k, my_double);
printf("%.15lf\n", *my_double);
}
void power_of_ten(int k, double *my_dbl)
{
double result = 1.0;
if(k >= 0){
for(int i = 0; i < k; i++) result = result*10.0;
} else{
for(int i = 0; i < (0-k); i++) result = result/10.0;
}
// printf("%f\n", result);
*my_dbl = result;
}
The pointer was never initialized. Easiest fix is:
int main(int argc, char **argv)
{
int k;
double my_double;
k = argc > 1 ? strtol(argv[1], NULL, 10) : 5;
power_of_ten(k, &my_double);
printf("%.15lf\n", my_double);
}
In the original code, the uninitialized pointer my_double does not yet point to a valid memory location, so the attempt to write to *my_dbl in the function fails. It basically writes data to some random place in memory. A different fix would be something like: double value; double *my_double = &value. Another might be double my_double[1]. Whatever you do, the address you referenced needs to be a place to which writes are valid.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
#include <stdio.h>
int isPrime(int n){
int ndiv = 0;
int i;
for(i=1;i<=n;i=i+1){
if(n%i == 0){
ndiv = ndiv+1;
}
}
if(ndiv == 2){
return 1;
}
else{
return 0;
}
}
int nextPrime(int n){}
int main(){
int a = isPrime(7);
printf(a);
//printf(isPrime(4));
}
This code gives me a run time error, I think there's a problem here with the way I deal with data types while using a functions and the printf command, but I can't really figure it out. Help!
f in printf stands for "format". You need to supply a format string for printing: printf("%d\n", a)
Your isPrime is inefficient: you do not need to attempt dividing all the way up to the number itself. You could stop once you reach the square root of the number
Moreover, you could exit the loop early once you see that the number is not prime.
Once you fix these errors, your program would start running and producing the output that you expect.
Here is a small example of how to use printf. You can find more format specifiers here.
#include <stdio.h>
int main()
{
int a = 97;
int b = 98;
char hello[6] = "world";
printf("%d\n", a);
printf("%d\n", b);
printf("%s\n", hello);
return 0;
}
It is because your method of printing a variable is wrong. Here's the right one.
int main(){
int a = isPrime(7);
printf("%d",a);
}
I'm no C/C++ expert, but try
printf("%d", a);
%d is a format placeholder expecting an integer number, essentially.
That looks like an interesting isPrime function. Not very efficient at all, but different from what I have seen in the past. You can also loop over all the numbers between 1 and n, and just return false (or 0) if you find any that divise n. Or look up more efficient algorithms.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to learn C but my code is not running properly.It always gives fatal error.I think there is a problem in for loop.How can i fix it?
#include<stdio.h>
int main( void )
{
int a ;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b = 1;
b *= i;
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
if(a==0) Not assignment use comparison.
You wanted to use the comparison but you ended up using assignment.
if(a=0) is same as if(0) so else part is executed.1
But that part also looks for a>0 which is not the case.
So it prints FATAL ERROR.
1. This happens because the result of an assignment expression is the value of the expression
What do I need to do to calculate factorial?
fact(0)=1
fact(1)=1
fact(n)=n*fact(n-1);
so you will do something like
for(int i=1;i<=a;i++)
b*=i;
You don't need that b=1 part because it is making everything 1. So your calculated value is not retained.
So the complete corrected code will be
#include<stdio.h>
int main()
{
int a;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b *= i; // don't overwrite value of b with 1
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
There are two major issues.
First being your use of if(a=0) which results in assignment in place of comparison which is achieved by if(a==0).
Secondly
for(i=1 ; i<=a ;i++)
{
b = 1;
b *= i;
}
This piece of code is faulty too. You are making b=1 after every iteration which overwrites the intermediate results Hence resulting in incorrect answer. As you have already initialized b to 1 in your code, you do not need this line at all.
for(i=1 ; i<=a ;i++)
{
b *= i;
}
Also it is worth mentioning that the reason you are always getting fatal error is because of what you are doing in the if condition. Due to if(a=0), variable a is assigned value 0 . Hence not satisfying both if and else if conditions and resulting in the execution of else block every time.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am working on CS50 PSET1. I have the following code so far:
#include <stdio.h>
#include <cs50.h>
int main(void) {
float change;
do {
printf("Change: ");
change = get_float();
} while(change < 0);
int coins;
for(int q = change; q < 25; q++) {
q = 25 / q;
coins += 1;
}
printf("%i", coins);
}
I am having an issue. When I try to compile my code with the make command I get an error saying this
greedy.c:17:9: error: variable 'coins' is uninitialized when used here [-> Werror,-Wuninitialized]
coins += 1;
The compiler is correct. You never assign anything to coins in the first place. All you do is increment its (uninitialized) value.
To assign an initial value, write
int coins = 0; /* or whatever the correct initial value is */
As an aside, I'm not quite sure what the intent is, but the following is highly unlikely to be what you want:
for(int q = change; q < 25; q++) {
q = 25 / q;
Note how the assignment modifies the loop variable. While this is permissible, in this context it looks unlikely to be intentional.