【问题标题】:Debugging code in C在 C 中调试代码
【发布时间】:2013-02-01 21:35:38
【问题描述】:

谁能告诉我我的代码有什么问题以及为什么会产生这个输出。

代码:

int main(){
  unsigned num;
  char response;

do{
 printf("Please enter a positive integer greater than 1 and less than 2000: ");
 scanf("%d", &num);
 if (num > 1 && num < 2000){
    printf("All the prime factors of %d are given below: \n", num);
    printPrimeFactors(num);
    printf("\n\nThe distinct prime factors of %d are given below: \n", num);
    printDistinctPrimeFactors(num);
 }
 else{
    printf("\nSorry that number does not fall between 1 and 2000.\n");
 }
 printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
 getchar();
 response = getchar();
}
while(response == 'Y' || response == 'y'); // if response is Y or y then program runs again
printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
return 0;
}

输出:

Please enter a positive integer greater than 1 and less than 2000: 1600
All the prime factors of 1600 are given below: 
2 2 2 2 2 2 5 5 

The distinct prime factors of 1600 are given below: 
2 5 

Do you want to try another number? Say Y(es) or N(o): yes
Please enter a positive integer greater than 1 and less than 2000: All the prime factors of 1600 are given below: 
2 2 2 2 2 2 5 5 

The distinct prime factors of 1600 are given below: 
2 5 

Do you want to try another number? Say Y(es) or N(o): Thank you for using my program. Good     Bye!

【问题讨论】:

  • 好像没什么问题! 1600的质因数是2、2、2、2、2、2、5、5
  • 是的......如果你看到我输入“是”的时候会很奇怪
  • 不是主要因素的实际代码...而是用户输入产生的输出
  • 您是否尝试在调试器中单步执行代码以查看发生了什么?提示 - getchar() 只读取一个字符。当您再次调用scanf() 时,输入流上会留下什么?提示 2 - 查看fgets(3)
  • @CarlNorum 我的教授(是的,这是“家庭作业”)希望我们使用 getchar() 来完成这项任务。使用 scanf 可以解决这个问题,对吧?但是,我必须使用 getchar()...

标签: c debugging output


【解决方案1】:

当您询问是否要重复时,您只阅读y,而es 在标准输入中排队。当您阅读下一个数字时,scanf 会尝试将其解析为数字,但失败并返回而不更改 num。当你提示用户时,你需要烧掉整行。

【讨论】:

    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多