[ create a new paste ] login | about

Link: http://codepad.org/TufNYnks    [ raw code | output | fork | 16 comments ]

C, pasted on Aug 17:
#include<stdio.h>
#include<conio.h>

int main()
{
	int i, n;
	float S;
	S = 0; i = 1;
	do
	{
		printf("\nNhap n: ");
		scanf("%d", &n);
		if(n < 1)
		{
			printf("\nN phai lon hon hoac bang 1. Xin nhap lai !");
		}

	}while(n < 1);

	while(i <= n)
	{
		S = S + 1.0 / i;  // phải nhớ là 1.0 / i
		i++;
	}
	printf("i = %d", i);
	printf("\nS = %f", S);
	printf("\nTong 1 + 1/2 + ... + 1/%d la %.2f: ",n, S);

	getch();
	return 0;
}


Output:
1
Line 17: error: conio.h: No such file or directory


Create a new paste based on this one


Comments:
posted by tanphu134 on Apr 8
tại sao dòng cuối lại return 0; là sao vậy bạn. mình không hiểu lắm.
reply
posted by khanhtienfz on Jun 24
Ko cần return 0 cũng được nhưng sẽ chính xác và đúng hơn nếu ta thêm vào.(0 có nghĩa tất cả hoạt động tốt)

reply
posted by duongthcsgiaothuy on Aug 19
return 0 là trả giá trị đầu về 0 mà
reply
posted by lehuong on Mar 6
vì int main thì có trả về bạn. vd void main: thì ko có trả về return
reply
posted by huntglory on Oct 12
co cach nao lam ma khong can dung lenh for while do ko????

reply
posted by hochoi1368 on Dec 2
tại sao chỗ kia lại phải là 1.0 / i ạ, nếu nhập 1/i thì sao ạ?


reply
posted by namphuong1908 on Aug 21
vì s là kiểu float. 1.0 nó sẽ ép kiểu sang dạng float
reply
posted by ntdung1001 on Apr 21
thanks.

reply
posted by hieunv1996 on Nov 19
Tôi đến từ khóa học lập trình C miễn phí của anh Hiếu
https://nguyenvanhieu.vn/khoa-hoc-lap-trinh-c/
reply
posted by hellboynice102 on Feb 1
#include <iostream>
using namespace std;

int main ()
{
int n;
cin >> n;
double s = 0;
for (int i = 1; i <= n; i++)
{
s = (double) 1 / i + s;
}
cout << s;
return 0;
}

reply
posted by 3119410294 on Apr 14
ths

reply
posted by incarnation16 on May 21
#include <stdio.h>

void SUM(int n)
{
float sum = 0;
for (int i = 1; i <= n; i++)
{
sum += 1.0 / i;
}
}
int main()
{
int n;
do
{

scanf("%d", &n);
} while (n < 1);

SUM(n);
printf("%.2f", SUM);
return 0;
}
Tai sao code k chay vay mn?
reply
posted by klefo on Jan 11
bạn dùng code c++ hay code c ?
reply
posted by klefo on Jan 11
#include <stdio.h>

float SUM(int n)
{
float x = 0;
for (int i = 1; i <= n; i++)
{
x += 1.0 / i;
}
return x;
}
int main()
{
int n;
do
{
scanf("%d", &n);
if(n < 1)
{
printf("\nerror, wrong input !");
}
} while (n < 1);

float a = 0;
a = SUM(n);
printf("%.5f", a);
return 0;
}

cậu xem lại code này nhá
reply
posted by cauco_melon on Aug 20
tại sao đặt điều kiện > 1. chỉ cần khác 0 thôi mà nhỉ? Ai giải thích giúp mình với
reply
posted by klefo on Jan 11
vì ta đặt i bằng 1 rồi nên chúng ta sẽ cộng bắt đầu từ 1/1 trở lên chứ không tính từ 1 nữa
reply