C语言百分比计算程序运行异常,请求问题排查与解决
问题分析与修复方案
你的程序运行异常主要源于三个核心错误:
1. 数组越界访问
printf("\nPlease enter the value of %s:\n", name1[25]); 中,name1[25]是访问数组的第26个元素(C语言数组下标从0开始,name1[25]的有效下标范围是0-24),属于数组越界操作,会触发未定义行为,直接导致程序崩溃或异常退出。正确写法是直接传入数组名name1。
2. 输入缓冲区残留问题
scanf("%i", &value1); 读取整数后,会将用户输入的换行符留在输入缓冲区中,后续的fgets会直接读取这个换行符,误认为用户输入了空内容,导致程序跳过后续输入步骤直接结束。需要在每次scanf后清空输入缓冲区。
3. 变量赋值错误
所有scanf都指向&value1,会导致后续输入的数值全部覆盖value1的值,value2到value5始终未被赋值,完全不符合程序设计逻辑,需对应修改为&value2、&value3等。
另外,fgets会将用户输入的换行符一并读取到数组中,打印时会多出换行,建议用strcspn去除换行符。
修正后的完整代码
#include <stdio.h> #include <string.h> int main (){ char name1[25] ; char name2[25] ; char name3[25]; char name4[25]; char name5[25]; int value1 ; int value2 ; int value3 ; int value4 ; int value5 ; printf ("Hello mortal, this program allows you to calculate percentages of five parts that are the only components of the whole.\n"); // 第一个变量输入 printf ("\nPlease enter your 1st variable that you want to calculate the percentage of without any spaces:\n"); fgets (name1, 25, stdin); // 去除fgets读取的换行符 name1[strcspn(name1, "\n")] = '\0'; printf ("\nPlease enter the value of %s:\n", name1); scanf ("%i", &value1); // 清空scanf残留的换行符 while(getchar() != '\n'); // 第二个变量输入 printf ("\nPlease enter your 2nd variable that you want to calculate the percentage of without any spaces:\n"); fgets (name2, 25, stdin); name2[strcspn(name2, "\n")] = '\0'; printf ("\nPlease enter the value of %s:\n", name2); scanf ("%i", &value2); while(getchar() != '\n'); // 第三个变量输入 printf ("\nPlease enter your 3rd variable that you want to calculate the percentage of without any spaces:\n"); fgets (name3, 25, stdin); name3[strcspn(name3, "\n")] = '\0'; printf ("\nPlease enter the value of %s:\n", name3); scanf ("%i", &value3); while(getchar() != '\n'); // 第四个变量输入 printf ("\nPlease enter your 4th variable that you want to calculate the percentage of without any spaces:\n"); fgets (name4, 25, stdin); name4[strcspn(name4, "\n")] = '\0'; printf ("\nPlease enter the value of %s:\n", name4); scanf ("%i", &value4); while(getchar() != '\n'); // 第五个变量输入 printf ("\nPlease enter your 5th variable that you want to calculate the percentage of without any spaces:\n"); fgets (name5, 25, stdin); name5[strcspn(name5, "\n")] = '\0'; printf ("\nPlease enter the value of %s:\n", name5); scanf ("%i", &value5); while(getchar() != '\n'); // 百分比计算逻辑 int total = value1 + value2 + value3 + value4 + value5; printf("\n--- 百分比结果 ---\n"); printf("%s: %.2f%%\n", name1, (float)value1 / total * 100); printf("%s: %.2f%%\n", name2, (float)value2 / total * 100); printf("%s: %.2f%%\n", name3, (float)value3 / total * 100); printf("%s: %.2f%%\n", name4, (float)value4 / total * 100); printf("%s: %.2f%%\n", name5, (float)value5 / total * 100); return 0; }
内容的提问来源于stack exchange,提问作者Bruno Duarte
相关产品推荐
相关产品推荐

