Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Learn Typing

تحديات برمجيةالتحدي السابع - حل التمرين الخامس بلغة جافا

المطلوب

أكتب برنامج يطلب من المستخدم إعطائه عدد صحيح أكبر من صفر و خزنه في المتغير n.
بعدها يقوم بحساب القيمة النهائية التي سيتم تخزينها في المتغير s.



الحل بلغة جافا

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int f;
int n = 0;
int s = 0;
do
{
System.out.print("Enter a number: ");
n = input.nextInt();
}
while (n <= 0);
for (int i = 1; i <= n; i++)
{
f = 1;
for (int j = 1; j <= i + 1; j++)
{
f *= j;
}
if (i % 2 == 1)
{
s -= i + f;
}
else
{
s += i + f;
}
}
System.out.println("S = " + s);
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int f; int n = 0; int s = 0; do { System.out.print("Enter a number: "); n = input.nextInt(); } while (n <= 0); for (int i = 1; i <= n; i++) { f = 1; for (int j = 1; j <= i + 1; j++) { f *= j; } if (i % 2 == 1) { s -= i + f; } else { s += i + f; } } System.out.println("S = " + s); } }

سنحصل على النتيجة التالية إذا قام المستخدم بإدخال الرقم 4 عند التشغيل.

Enter a number: 4
S = 102