我需要在C中創建一個代碼,它讀取一系列數字,第一個數字是產品編號(介於1和產品總數之間)通過輸入),第二個數字是1-10的評分,並將其存儲在二維數組中。從1開始的數組行是產品編號,1-10列是評級。第11列是星星的總數,第12列是總分數。我必須使用scanf來讀取值,並且當scan()!= 2時,循環應停止並生成報告。如何停止讀取輸入並分析數據C
報告應列出每種產品的評分數量(即2個評分爲5星,17個評分爲10星等)以及平均評分。
我想我的邏輯是正確的,我的代碼編譯了,但是當我嘗試生成一個報告時,它一直返回錯誤。任何線索的問題可能是什麼?
這是我到目前爲止的代碼:你從標準輸入一排,我要做到不認爲兩次讀取
int productStar[][13] = {0};
int i = 0;
int product = 0;
int stars = 0;
int howMany = 0;
int ratings = 0;
float avg = 0;
int sum = 0;
printf("How many unique products?\n");
scanf("%d", &howMany);
printf("Please enter product # and stars\n");
while(1)
{
scanf("%d %d", &product, &stars); /* Reads in two values; first is product number, second is rating */
if (scanf("%d %d", &product, &stars) != 2) /* kills the loop */
{
printf("Hi from the inside\n");
break;
}
productStar[product][stars] += 1; /* adds tally to specific product rating */
productStar[product][11] += stars; /* increments total number of stars; used later to find avg */
productStar[product][12] += 1; /* increments how many ratings */
}
for (int product = 0; product <= howMany; ++product)
{
for (int stars = 0; stars <= 10; ++stars)
{
avg = productStar[product][11]/productStar[product][12];
printf("Product %d Information:\n", product);
printf("1 star: %d\n", productStar[product][1]);
printf("2 star: %d\n", productStar[product][2]);
printf("3 star: %d\n", productStar[product][3]);
printf("4 star: %d\n", productStar[product][4]);
printf("5 star: %d\n", productStar[product][5]);
printf("6 star: %d\n", productStar[product][6]);
printf("7 star: %d\n", productStar[product][7]);
printf("8 star: %d\n", productStar[product][8]);
printf("9 star: %d\n", productStar[product][9]);
printf("10 star: %d\n", productStar[product][10]);
printf("Average rating: %2.2f out of 10 (%d ratings total).\n", avg, ratings);
printf("--------------------\n");
}
}
for (product = 0; product <= howMany; ++product)
{
sum += productStar[product][12];
/* Sum of all ratings */
}
printf("%d product ratings evaluated in all.\n\n", sum);
return 0;
}
所有這些'的printf( 「1星:%d \ n」,productStar [產品] [1]);'線可以換成只有一個insi de一個for循環。 –
你收到什麼樣的錯誤信息?我想這可能與你的'int productStar [] [13] = {0};'初始化... – Zexus