So recently I've been learning how to code in University (this is only my second semester and the first semester for programming with Java was easy as hell). I have a very simple question which I have been confused on (this is my first time attempting C++, literally only just got Eclipse C++ working today). The question is simply: "Create a C++ program to calculate 1 + ½ + 1/3 + ¼ +…+ 1/n, where n can be any positive integer". It seems simple, however the code I have written doesn't seem to be receiving the desired output. Here''s my code so far:
#include <iostream>
using namespace std;
int main()
{
int n;
int i = 1;
cout << "Enter a value for n.";
cin >> n;
int total = 0;
while (i < n)
{
total = total + 1/i;
i++;
}
cout << "1 + 1/2 + 1/3 + ... + 1/n = " << total;
return 0;
}
All that gets outputted (no matter which number I input for n) is:
1 + 1/2 + 1/3 + ... + 1/n = 1
I apologize if there has already been a thread similar this, if so a link to it would be appreciated, also any tips for coding would also be appreciated. I realise that this is an easy piece of code that anyone experienced would probably figure out what was wrong withing seconds, and I have coded a pacman like game in Java before and even made a crappy mario-ish game on game maker, I just have no idea what I'm doing in C++. Maybe I'm just having a brain fart idk haha thanks :)