D
D
dmitry_dev332016-11-09 21:30:17
C++ / C#
dmitry_dev33, 2016-11-09 21:30:17

Please find an error in the c++ code?

The program should convert numbers from 10 to binary, but for some reason it doesn't work. Maybe there is some extra included?

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <locale>

int main()
{
  setlocale(LC_ALL, "RUSSIAN");
  int denary; //вводимое число в 10-системе
  int power; //наибольшая степень двойки
  int counter; // счётчик циклов

    printf("\n Введите число от 0 до 255     ");
    scanf_s("%d", &denary);
    if (denary > 255)
      {
        printf("\n Ошибка исходных данных\n");
        getchar();
        exit(0);
      }
      power = 128;
      printf("\n");
      for (counter = 1; counter <= 8; counter++);
      {
        if (denary >= power)
          {
            printf("1");
            denary = denary - power;
          }
        else
          {
            printf("0");
            power = power / 2;
          }
      }
      printf("\n Двоичный код числа =%4d \n", denary);
    
    return 0;
}

abb94fe926f04fcbb86ed919162887b8.jpg

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nexeon, 2016-11-09
@dmitry_dev33

Remove the semicolon ;at the end of the linefor (counter = 1; counter <= 8; counter++);

G
GavriKos, 2016-11-09
@GavriKos

Firstly - all the code in the "code" tag!
Secondly, if there are errors in the includes, the program will not compile.
Thirdly - in my opinion you are doing something completely wrong. Algorithmically.

R
Rsa97, 2016-11-09
@Rsa97

The first error is ; after for
Second - power must be reduced in each iteration.
Well, general inefficiency.

for (power = 128; power > 0; power >>= 1)
  printf((denary & power ? "1" : "0");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question