This is the C problem and i need your help.
I have checked my code lots of time but I can not print out the result. Question: input n and print out S = 1-1/2 1/3-1/4... -1/n with abs(1/n)>e
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
float checkQ3(int n){
float sum = 0;
for(int i = 0; i<= n; i ){
if(i % 2 == 0){
sum = -1/i;
}else{
sum = 1/i;
}
}
return sum;
}
int main(){
int n; printf("Input n: "); scanf("%d",&n);
float sum1 = checkQ3(n);
printf("%f",sum1);
}
Then there is no ouput, I have tried so many way but it did not work,please help me.
CodePudding user response:
Your for
loop starts at 0, rather than one resulting in division-by-zero. Edit your code to the following:
for(int i = 1; i<= n; i ){
if(i % 2 == 0){
sum = -1/i;
}else{
sum = 1/i;
}
}
CodePudding user response:
YOu need to distinguish
- my program ran but gave the wrong result
- my program crashed because I asked to do something impossible
Yours is the second one
I got
Unhandled exception at 0x00007FF695651997 in ConsoleApplication3.exe: 0xC0000094: Integer division by zero.
You must surely have got a similar error message too
Anyway run this code in your head with i == 0
for (int i = 0; i <= n; i ) {
if (i % 2 == 0) {
sum = -1 / i; <<<<<========
CodePudding user response:
Start your loop form 1
So that you don't face any exception
for (i = 1; i <= n; i )
s = i%2==0 ? -1/i : 1/i;
return s;