+ 2
c++ : inpunt an integer N. get the average of all odd number from 1 to N.
i can't figure it out. thanks!
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
+ 22
if n is odd ... then output (n+1)/2
else output n/2
//☺👍
+ 20
now see ☺
//now its correct in java as well as mathematically correct
+ 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
+ 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 ;)
+ 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 :(
+ 1
you never mentioned java and i interpret formulas mathematically :p
+ 1
wait, what exactly is it you cant do now?
+ 1
i dont know how to add all the output number and get the average..can you help me complete the code? :)
+ 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