+ 2

c++ : inpunt an integer N. get the average of all odd number from 1 to N.

i can't figure it out. thanks!

24th Jan 2018, 7:03 PM
Angelo
Angelo - avatar
10 Réponses
+ 3
just use a for loop that starts from 1 and increses in +2 steps. add them all together and divide it by the amount of loops
24th Jan 2018, 7:11 PM
Jeremy
Jeremy - avatar
+ 22
if n is odd ... then output (n+1)/2 else output n/2 //☺👍
24th Jan 2018, 7:35 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 20
now see ☺ //now its correct in java as well as mathematically correct
24th Jan 2018, 7:45 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
useless comment because @gaurav corrected his comment original comment: let n = 5 sum of all odds is 1+3+5=9 average is 9/3= 3 output = 3 your formula: (5/2)+1= 3.5 3 != 3.5 correct me if im wrong
24th Jan 2018, 7:40 PM
Jeremy
Jeremy - avatar
+ 2
#include <iostream> using namespace std; int main() { int x,y; cout<<"input a number: "; cin>>x; for(int i=0;i<x;i++){ i=i+1; y=i; cout<<y<<endl; } return 0; } i know how to get the average literally.. but i dont know how to add all of the output number N then get the average.. thanks for the replies ;)
24th Jan 2018, 7:41 PM
Angelo
Angelo - avatar
+ 2
by the way I forgot to add, the problem is you don't need an if and else if statement.. that's y i cant fighre it out :(
24th Jan 2018, 7:46 PM
Angelo
Angelo - avatar
+ 1
you never mentioned java and i interpret formulas mathematically :p
24th Jan 2018, 7:42 PM
Jeremy
Jeremy - avatar
+ 1
wait, what exactly is it you cant do now?
24th Jan 2018, 7:50 PM
Jeremy
Jeremy - avatar
+ 1
i dont know how to add all the output number and get the average..can you help me complete the code? :)
24th Jan 2018, 7:53 PM
Angelo
Angelo - avatar
+ 1
double sum = 0; int counter = 0; for(int i = 1; i ≤ n; i+=2){ sum += i; counter++; } double average = sum/counter; or you use the formulars from above which gaurav provided
24th Jan 2018, 8:01 PM
Jeremy
Jeremy - avatar