|
发表于 2023-11-19 15:47:53
|
显示全部楼层
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char a[51]; // 修改数组长度为51,以容纳最长的50位整数和字符串结尾的'\0'
- double x = 0, y, count = 0;
- int i;
- gets(a);
- for (i = 0; a[ i] != '\0'; i++)
- {
- if (a[ i] == '2')
- {
- count++;
- }
- }
- if ((a[i - 1] - 48) % 2 == 0) // 修改为a[i - 1] - '0'以获取最后一位数字
- {
- x += 2.0;
- }
- if (a[0] == '-')
- {
- x += 0.5;
- y = (count / (double)(i - 1.0)) * x * 2.0 * 0.01;
- }
- else
- {
- y = (count / (double)i) * x * 2.0 * 0.01;
- }
- printf("%.2lf", y);
- }
复制代码
在您的代码中,有几个问题需要修复:
1. 由于输入的整数可能是50位,因此需要将数组长度增加到51,以便容纳最长的整数和字符串结尾的'\0'。
2. 在计算最后一位数字时,应该使用 a[i - 1] - '0' 而不是 a[i - 1] - 48 。
3. 在计算犯二程度时,应该使用 (count / (double)i) 而不是 (count / (double)(i - 1.0)) ,因为 (i - 1.0) 实际上是数组中的'\0'的位置,而不是整数的位数。
以上是修改后的代码,应该可以正确计算给定整数的犯二程度并输出结果。 |
|