[C/C++]疑似底层出现的问题

代码片段

#include<bits/stdc++.h>

using namespace std;
bool check2(int n)
{
    int a=n;
    char str[10];
	sprintf(str,"%d",a);
    for(int i=0;i<10;i++){
        if(str[i]=='2'||str[i]=='4'){
            return 0;
        }
    }
	return 1;
}
bool check1(int x) {	//判断三个正整数中是否含2或4 
	int res = 0;
	while (x) {
		res = x % 10;
		if (res == 2 || res == 4) return 0;
		x /= 10;
	} 
	return 1;
}
int main()
{    int ans_1=0;
int ans_2=0;
    for(int i=1;i<2019;i++){
        for(int j=i+1;j<2019;j++){
            for(int k=j+1;k<2019;k++){
                if(i+j+k==2019&&check1(i)&&check1(j)&&check1(k)){
                    ans_1++;
                }
                if(i+j+k==2019&&check2(i)&&check2(j)&&check2(k)){
                    ans_2++;
                }
            }    
        }
    }cout<<"ans_1:"<<ans_1<<endl; 
    cout<<"ans_2:"<<ans_2<<endl; 
    
    
    
    int ans1=0;
    int ans2=0;
    int ans3=0;
    for(int i=1;i<2019;i++){
                if(check1(i)){
                    ans1++;
                }
                
            	if(check2(i)){
                    ans2++;
                }
                
                if(check1(i)&& check2(i)){
                    ans3++;
                }
    }cout<<"ans1:"<<ans1<<"\nans2:"<<ans2<<"\nans3:"<<ans3<<endl; 
    
    
    
    return 0;
}

结果

在这里插入图片描述

问题解决

char数组初始化赋值解决,但下方ans1ans2却正常运行原理还需探究。

int check2(int n)
{
    int a=n;
    char str[10]="";需要初始化赋值
	sprintf(str,"%d",a);
    for(int i=0;i<10;i++){
        if(str[i]=='2'||str[i]=='4'){
            return 0;
        }
    }
	return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值