اذهب إلى المحتوى
  • 0

ما الخطأ في شيفرة C++ التالية؟

محب روفائيل

السؤال

#include <iostream>

using namespace std;

int factorial(int number, int result) {
	
	
	result = result * number;
	
	number--;
	
	if (number >= 1) {
		factorial (number, result);
	} else {
		return result;
	}
}

int show_multiply (int number) {
	
	for (int i = number; i >= 1; i--) {
		
		cout << i;
		if (i != 1) {
			cout << " x ";
		}
	}
	return 0;
}

int main() {
	int number, result = 1;
	
	cout << "Enter the number you need its factorial:\n";
	cin >> number;
	
	int fact_result = factorial(number, result);

	cout << "To compute the factorial of " << number << " , you must multiply " << show_multiply(number) << " So the factorial of " << number << " is " << fact_result;
}

الناتج يكون كالتالي:

Enter the number you need its factorial:
5
5 x 4 x 3 x 2 x 1To compute the factorial of 5 , you must multiply 0 So the factorial of 5 is 120

 

لكني أريد أن تظهر الأعداد:

  5x 4 x 3 x 2 x 1

بدلا من الصفر

 

أعتقد أن اﻷمر له علاقة ب return 0 في دالة show_mulltiply، لكن لم أعرف كيف أحلها..

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0
#include <iostream>
#include <sstream>

using namespace std;

int factorial(int number) {
  if (number < 0)
    return false;
  if (number == 0)
    return 1;
  return number * factorial(number - 1);
}

void show_multiply (int number) {
  stringstream res;
  for (int i = number; i > 1; i--) {
  	res << i << " x ";
  }
  res << "1";
  cout << res.str();
}

int main() {
  int x = 5;
  int fact = factorial(x);
  show_multiply(x);
}

أولاً: لحساب الـ factorial انت بحاجة بس لـ parameter واحد.

ثانياً: لا تستخدم تابع show_multiply ضمن cout.

الخطأ عندك انو تابع show_multiply عم تساوي جواتو تعليمات cout، والخرج تبعو من النمط int، ومو محدد خرج لإلو إلا return 0 لهيك دائماً عم يخرج 0

الحل: إما تخلي تابع show_multiply يساوي تعليمات cout، وبدون خرج، وبالتالي لح يطبع 5x4x3x2x1، وما تستدعيه ضمن cout تانية خارجية (وهاد الحل يلي استخدمتو بالكود تبعي)

أو إنك تخلي خرج التابع show_multiply من النمط string، وتعملو cout من برا.

تم التعديل في بواسطة عمار الشيخ
رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...