这是 Programming in c 第7章第3题
/*这个程序的目的就是给某个东西打分,可以是1~10,想看一下有几个1分,有几个2分……有几个10分*/
#include<stdio.h>
int main(void)
{
int i, response, number;//i 用于循环, response用于输入打的分数, number表示有多少个人参与了打分
int ratingCounters[11];//用来存储每个分数的个数
printf (“Enter the number of responses: “);
scanf (“%i”, &number);
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;//每个分数的个数起始值都是0
printf (“Enter your resonses.\n”);
//输入number次分数1~10为有效值
for (i = 1; i <= number; ++i){
scanf (“%i”, &response);
//输入小于1或大于10的值会发出提示且不计入ratingCounters数组
if (response < 1 || response > 10)
printf (“Bad response: %i\n”, response);
else
++ratingCounters[response];//输入有效值则对应分数的个数+1
}
//按指定格式输出最后各个分数的个数
printf (“\n\nRating Number of Responses\n”);
printf (“– –\n”);
for (i = 1; i <= 10; ++i)
printf (“%4i%14i\n”, i, ratingCounters[i]);
return 0;
}
经过尝试 发现问题出在这个地方:
scanf (“%i”, &number);
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;
假如按这个顺序, 则在输入完number后,会跨过输入response的循环体,直接运行按格式输出;
假如调换上述两行的顺序:
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;
scanf (“%i”, &number);
就可以正常运行。
用程序可视化运行到for (i = 1; i <= number; ++i)这个循环体的时候,会出现提示“ERROR: Conditional jump or move depends on uninitialised value(s) (Stopped running after the first error. Please fix your code.)”
本人感觉问题出现在number的初始化上。但找不到头绪。还望高手指点一二
/*这个程序的目的就是给某个东西打分,可以是1~10,想看一下有几个1分,有几个2分……有几个10分*/
#include<stdio.h>
int main(void)
{
int i, response, number;//i 用于循环, response用于输入打的分数, number表示有多少个人参与了打分
int ratingCounters[11];//用来存储每个分数的个数
printf (“Enter the number of responses: “);
scanf (“%i”, &number);
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;//每个分数的个数起始值都是0
printf (“Enter your resonses.\n”);
//输入number次分数1~10为有效值
for (i = 1; i <= number; ++i){
scanf (“%i”, &response);
//输入小于1或大于10的值会发出提示且不计入ratingCounters数组
if (response < 1 || response > 10)
printf (“Bad response: %i\n”, response);
else
++ratingCounters[response];//输入有效值则对应分数的个数+1
}
//按指定格式输出最后各个分数的个数
printf (“\n\nRating Number of Responses\n”);
printf (“– –\n”);
for (i = 1; i <= 10; ++i)
printf (“%4i%14i\n”, i, ratingCounters[i]);
return 0;
}
经过尝试 发现问题出在这个地方:
scanf (“%i”, &number);
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;
假如按这个顺序, 则在输入完number后,会跨过输入response的循环体,直接运行按格式输出;
假如调换上述两行的顺序:
for (i = 1; i <= 11; ++i)
ratingCounters[i] = 0;
scanf (“%i”, &number);
就可以正常运行。
用程序可视化运行到for (i = 1; i <= number; ++i)这个循环体的时候,会出现提示“ERROR: Conditional jump or move depends on uninitialised value(s) (Stopped running after the first error. Please fix your code.)”
本人感觉问题出现在number的初始化上。但找不到头绪。还望高手指点一二
解决方案
20
数组越界。
int ratingCounters[11];//用来存储每个分数的个数
这个数组的合法范围是0~10,而不是1~11
所以,
for (i = 1; i <= 11; ++i) 应该是 for (i = 0; i < 11; ++i)
int ratingCounters[11];//用来存储每个分数的个数
这个数组的合法范围是0~10,而不是1~11
所以,
for (i = 1; i <= 11; ++i) 应该是 for (i = 0; i < 11; ++i)