一个整数“犯二的程度”定义为该数字中包含2的个数与其位数的比值。如果这个数是负数,则程度增加0.5倍;如果还是个偶数,则再增加1倍。例如数字-13142223336是个11位数,其中有3个2,并且是负数,也是偶数,则它的犯二程度计算为:3/11×1.5×2×100%,约为81.82%。本题就请你计算一个给定整数到底有多二。
输入格式:
输入第一行给出一个不超过50位的整数N。
输出格式:
在一行中输出N犯二的程度,保留小数点后两位。
输入样例:
-13142223336
结尾无空行
输出样例:
81.82%
结尾无空行
我不知道我写的哪里错了
#include "stdio.h"
int main()
{
int N,A,B;
double u,t,D;
scanf("%d",&N);
while(N!=0){
A++;
if(N%10==2){
B++;}
N/=10;
}
t=A;
u=B;
if((N>0)&(N%2!=0)){
D=u/t;
printf("%.2lf%%",D*100);
}else
if((N<0)&(N%2!=0)){
D=1.5*u/t;
printf("%.2lf%%",D*100);
}else
if((N>0)&(N%2==0)){
D=2*u/t;
printf("%.2lf%%",D*100);
}else
if((N<0)&(N%2==0)){
D=3*u/t;
printf("%.2lf%%",D*100);
}
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
string s;
cin >> s;
int cnt = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '2') cnt++;
}
if (s[0] == '-')
{
if (s[s.length() - 1] % 2 == 0)
{
printf("%.2lf%%\n", (double)cnt / (s.length() - 1) * 1.5 * 2 * 100);
}
else
printf("%.2lf%%\n", (double)cnt / (s.length() - 1) * 1.5 * 100);
}
else
{
if (s[s.length() - 1] % 2 == 0)
{
printf("%.2lf%%\n", (double)cnt / (s.length()) * 2 * 100);
}
else
printf("%.2lf%%\n", (double)cnt / (s.length()) * 100);
}
return 0;
}
题主的if() 里 并且 是用一个 ‘&’ ,应该是 ‘&&’ ,一个是取地址。