#include<stdio.h>
int main(){
int N,weight=1,goal=2,countDigit=0,countGoal=0;
float value;
scanf("%d",&N);
if(N<0){
weight*=1.5;
N=-N;
}
if(N%2==0){
weight*=2;
}
if(N!=0){
countDigit++;
if(N%10==goal){
countGoal++;
}
N/=10;
}
value=countGoal/countDigit*weight*100;
printf("%.2f",value);
}
希望可以得到指导,更正。
这个条件是输入 N 不超过50位的数,显然用 int 型是不够的。修改如下,见注释,供参考:
#include <stdio.h>
int main()
{
char str[51] = { 0 };
int sign = 1, odd = 1, i = 0, n = 0;
float power = 1.0;
scanf("%s", str);
if (str[0] == '-') // 判断是否是 负数
{
sign = -1;
power += 0.5;
i++;
}
while (str[i]) // 统计 2 的个数
{
if (str[i] == '2')
n++;
i++;
}
if ((str[i-1] - '0') % 2 == 0) // 判断最后一位数是否是偶数
odd = 2;
if (sign == -1) i--; // 如果是负数,实际数值位数减去符号位所占 1 位
printf("%0.2f%%", n * 1.0 / i * power * odd * 100);
return 0;
}
可以使用字符数组来存储最多50位的整数,然后遍历这个整数字符串,判断是否为负数和是偶数,以及计算'2'的个数和位数,最后再计算最终比例即可。
修改如下:
#include<stdio.h>
#include <string.h>
int main(){
int N,goal=2,countDigit=0,countGoal=0;
float value,weight=1;
char num[52]; // 因为最多50位的整数,所以使用字符数组来存储输入的整数
//scanf("%d",&N);
scanf("%s",num);
// printf("num=%s\n",num);
int i=0;
if(num[0]=='-'){ // 如果为负数,则比例增加0.5倍
weight*=1.5;
// N=-N;
i++;
}
// printf("1、weight=%.2f\n",weight);
int last = (num[strlen(num)-1]-'0'); // 提取最后一位数字
if(last%2==0){ // 如果最后一位数字为偶数,则比例增加1倍
weight*=2;
}
// printf("2、weight=%.2f,last=%d\n",weight,last);
while(num[i]!='\0'){ // 遍历输入的整数字符串,计算'2'的个数,以及位数
if(num[i]=='2'){ // 如果当前字符为'2',则计数器 countGoal++
countGoal++;
}
countDigit++; // 位数计数器++
i++; //下标指向下一位
}
// printf("3、countGoal=%d,countDigit=%d\n",countGoal,countDigit);
// 计算最终比例 ,下面在 countGoal前面增加float,转换其类型,将前面的整数运算变为float类型计算,以保留小数结果
value=(float)countGoal/countDigit*weight*100;
//打印结果
printf("%.2f%%",value);
}
你怎么连循环都没有。应该用while构成循环。
【以下回答由 ChatGPT 生成】
#include <stdio.h>
int main(){
int N, weight=1, goal=2, countDigit=0, countGoal=0;
float value;
scanf("%d", &N);
if(N<0){
weight*=1.5;
N=-N;
}
if(N%2==0){
weight*=2;
}
if(N!=0){
countDigit++;
if(N%10==goal){
countGoal++;
}
N/=10;
}
value=(float)countGoal/countDigit*weight*100;
printf("%.2f", value);
return 0;
}
在原有代码的基础上,我只做了一个小小的修改,即将 value=countGoal/countDigit*weight*100;
改为 value=(float)countGoal/countDigit*weight*100;
。
原因是 countGoal/countDigit
是整数除法,结果将是整数,然后乘以 weight
和 100
后赋值给 value
,再进行输出时结果会被四舍五入成整数。
而我将 countGoal/countDigit
强制转换为浮点数,确保了小数点的精度。
希望对您有帮助!如果还有其他问题,请随时提问。
【相关推荐】