Câu 1.1: Viết hàm tính tổng s = 1 + 3 + 5 + … + (2*n + 1), với n nguyên dương. Viết chương trình nhập vào từ bàn phím số nguyên dương n, áp dụng hàm trên tính và in ra màn hình tổng tương ứng.
7:27 PM |
Ø code viết theo không empty
project trong visua c++.
//
bai1.cpp : Defines the entry point for the console application.
// code
Dũng NV
#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
int tong(int n)
{
int i;
int s=0;
for (i=0;i<=n;i++)
s+=(2*i+1);
return s;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
printf("\nNhap N=
");
scanf("%d",&n);
printf("\n Tong s = %d",tong(n));
getch();
return 0;
}
Ø Nếu code viết bằng Dev-C hay tích empty project trong visua c++.
Xóa thư viện #include "stdafx.h" ở đầu bài làm và return 0; ở hàm main.
Đổi int
_tmain(int argc, _TCHAR* argv[]) thành void main()
#include <conio.h>
#include <stdio.h>
int tong(int n)
{
int i;
int s=0;
for (i=0;i<=n;i++)
s+=(2*i+1);
return s;
}
void main()
{
int n;
printf("\nNhap N=
");
scanf("%d",&n);
printf("\n Tong s = %d",tong(n));
getch();
}
dungnv