我是C的新手。循环永远不会结束为什么会这样

问题描述 投票:-5回答:1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    float  n ,a, sum,count,count1;
    printf("\nInput integer in base 10 : ");
    scanf("%f", &n);
    for(count=0 ; count<=100 ; ++count){
        if(n/pow(2,count)<2 && n/pow(2,count)>=1)break;
    }
    a=n-pow(2,count);
    sum=pow(10,count);
    for(count1=count-1 ; count1>=0 ; --count){
        if(a/pow(2,count1)<2 && a/pow(2,count1)>=1 ){
            a-=pow(2,count1);
            sum+=pow(10,count1);
        }
    }
    printf("The binary of %.0f is %.0f",n,sum);
    return 0;
}

此代码用于打印十进制数的二进制等效值而不使用数组

c
1个回答
1
投票

正如@kiner_shah在对你的问题的评论中所述,你的第二个循环中有一个不正确的变量递减。

for(count1=count-1 ; count1>=0 ; --count){
    ...

应该

for(count1=count-1 ; count1>=0 ; --count1){
    ...

使用更多不同/描述性的变量名来避免单个字符错误是一个很好的习惯。

© www.soinside.com 2019 - 2024. All rights reserved.