It looks like there’s a small mistake in your code that’s causing the issue. You’re incrementing frequency1
in every case of your switch statement instead of incrementing the correct frequency variables. Here’s the corrected code:
cpp#include
#include
#include
#include
int main()
{
int face;
int frequency1 = 0;
int frequency2 = 0;
int frequency3 = 0;
int frequency4 = 0;
int frequency5 = 0;
int frequency6 = 0;
for (int counter = 1; counter <= 6000; counter++) {
face = 1 + rand() % 6;
switch (face) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
default:
std::cout << "program should never get here!!! ";
break;
}
}
std::cout << "the number of face 1 is : " << frequency1 << std::endl;
std::cout << "the number of face 2 is : " << frequency2 << std::endl;
std::cout << "the number of face 3 is : " << frequency3 << std::endl;
std::cout << "the number of face 4 is : " << frequency4 << std::endl;
std::cout << "the number of face 5 is : " << frequency5 << std::endl;
std::cout << "the number of face 6 is : " << frequency6 << std::endl;
return 0;
}
This should now correctly count the frequency of each face when the dice is thrown 6000 times.
-
كيفية إنشاء رمز وصول لصفحة فيسبوك19/03/2024
-
عد الكومنتات في منتدى05/03/2024
-
كيفية جعل روبوت Slack يترك قناة؟08/03/2024
المزيد من المعلومات
بالطبع! يبدو أنك تستخدم الدالة rand()
لتوليد أرقام عشوائية في الفترة من 1 إلى 6 لتمثيل وجوه النرد. ولكن هناك بعض الأمور التي يمكن تحسينها في الشفرة:
-
بادئة السطر
using namespace std;
: استخدام هذه البادئة يمكن أن يؤدي إلى تداخلات في أسماء الأشياء. بدلاً من ذلك، يفضل استخدامstd::
قبل اسم كل شيء من مكتبة الـStandard Library مثلcout
وendl
. -
عدم استخدام
std::setw
: قمت بتضمين
واستخدمتusing std::setw;
ولكن لم تستخدمsetw
في الشفرة. يمكنك استخدامsetw
لتهيئة عرض الأعمدة عند طباعة النتائج. -
التعليقات الإضافية: قم بإضافة تعليقات إلى الشفرة لتوضيح الأغراض والخطوات الرئيسية.
بالتالي، هناك تحسينات بسيطة يمكن إجراؤها لتحسين قراءة الشفرة وصيانتها. تعديل الشفرة بناءً على هذه الاقتراحات يمكن أن يكون كالتالي:
cpp#include
#include
#include
int main()
{
// Initialize variables to count the frequency of each face
int frequency[6] = {0};
// Seed the random number generator
srand(static_cast<unsigned int>(time(0)));
// Roll the dice 6000 times
for (int counter = 0; counter < 6000; counter++) {
int face = 1 + rand() % 6; // Generate a random number between 1 and 6
++frequency[face - 1]; // Increment the frequency of the corresponding face
}
// Print the results
for (int i = 0; i < 6; i++) {
std::cout << "the number of face " << i + 1 << " is : " << frequency[i] << std::endl;
}
return 0;
}
هذه التحسينات تجعل الشفرة أكثر وضوحًا وسهولة في الصيانة، مما يجعلها أكثر كفاءة.