【发布时间】:2014-09-19 02:09:25
【问题描述】:
我在使用不同方法的以下代码时遇到问题。 当我运行我的代码并输入 2 作为我的参数时,我得到一个零和一的无限循环。 我不确定那部分有什么问题。 任何帮助都会很棒。谢谢!
/*global variables*/
int CPI[];
int Count[];
每当我选择 1 作为我的参数时,我输入 3 作为我的指令类,但是我无法输入类 3 的 CPI 甚至是类 3 的指令数。一旦我输入类 2 的 CPI 和指令数结束。
void SelectOne(){
tot = 0;
printf("\n Enter the number of instruction classes: ");
scanf("%d", &n);
printf("\n Enter the frequency of the machine (MHz): ");
scanf("%d", &f);
int CPI[n];
int Count[n];
int a;
for(a = 1; a < n; a++){
/*printf("%d",n);*/
printf(" Enter CPI of class %d : ", a);
scanf("%d", &CPI[a-1]);
printf(" Enter instruction count of class %d : ", a);
scanf("%d", &Count[a-1]);
tot =+ Count[a-1];
}
}
这是我得到 0 和 1 的无限循环的方法。
void SelectTwo(){
printf("\n ---------------------------");
printf("\n +Class/t + CPI/t +Count +");
int a;
for(a = 1; a <= n; a++){
printf("\n %d\t + %d\t + %d ", a, CPI[a-1], Count[a-1]);
}
}
我相信我的问题是主要的,但我不确定如何解决这个问题。
int main(){
int sel = 1;
while(sel != 4){
printf("\n 1) Enter Parameters ");
printf("\n 2) Print table of parameters ");
printf("\n 3) Print table of performance ");
printf("\n 4) Quit");
printf("\n \n Enter Selection: ");
scanf("%d", &sel);
if(sel == 1){
SelectOne();
}
if(sel == 2){
SelectTwo();
}
if(sel == 3){
SelectThree();
}
else{
printf("quit");
}
}
}
【问题讨论】:
-
这看起来可能是错误的,但不会导致您的循环:
tot =+ Count[a-1];(C 中没有=+运算符)。您发布的代码中还有其他几个印刷错误。如果您手动复制它,您可能想尝试复制/粘贴。selectTwo()函数看起来不会进入无限循环。也许这只是一个很长的循环。进入函数时检查n的值。 -
这如何编译?您在
SelectOne()中定义int CPI[n],然后尝试在完全不同的函数SelectTwo()中访问它。这里肯定有一些你没有告诉所有人的事情。 -
@lurker 当我打印 n 时它返回它应该是的值,这是运行时输入的指令类的值。
-
@Csci01:当您定义一个全局数组而不指定其大小时,大小默认为 1。这就是您收到有关全局
CPI和全局Count大小为 1 的警告的原因.
标签: c if-statement for-loop