Ilya-Glushko 0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
||||
1 |
||||
21.01.2018, 15:11. Показов 22583. Ответов 19 Метки калькулятор систем счисления (Все метки)
При компиляции выдаёт вот такие ошибки: P.S Пробовал переставлять объявления и менял их, не помогает.
0 |
139 / 67 / 46 Регистрация: 15.10.2015 Сообщений: 308 |
|
21.01.2018, 15:21 |
2 |
Инициализируйте X и Y нулями.
0 |
3946 / 2860 / 665 Регистрация: 08.06.2007 Сообщений: 9,673 Записей в блоге: 4 |
|
21.01.2018, 15:23 |
3 |
РешениеПереставить строку 31 и поставить ее после 38-й. Добавлено через 1 минуту
Инициализируйте X и Y нулями. Это приведет к делению на нуль в строке 38.
1 |
139 / 67 / 46 Регистрация: 15.10.2015 Сообщений: 308 |
|
21.01.2018, 15:25 |
4 |
Это приведет к делению на нуль в строке 38. Ему не кто не запрещает инициализировать их 1. Я не читал код, так-как из самой ошибки понятно, в чем проблема.
1 |
pain1262 6 / 6 / 7 Регистрация: 24.09.2016 Сообщений: 63 |
||||
21.01.2018, 15:35 |
5 |
|||
0 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 15:42 [ТС] |
6 |
Спасибо, помогло. Добавлено через 3 минуты
0 |
7427 / 5021 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
21.01.2018, 16:11 |
7 |
Ilya-Glushko, сбросьте условие задачи
0 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 16:15 [ТС] |
8 |
Yetty, задачи поставленно небыло, я просто хотел сделать калькулятор с выбором умножения и деления, щас дорабатывать буду, кстати у меня ещё одна проблема…
0 |
7427 / 5021 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
21.01.2018, 16:20 |
9 |
Ilya-Glushko, дело не в инициализации (она вообще не нужна если не переназначать переменные), а в обработке возможной попытки деления на нуль.
0 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 16:40 [ТС] |
10 |
Yetty, Что вы предлагаете? Можете конкретно показать? Сразу оговорюсь если я использую std::, не запускается, так что не делайте на это расчет. З.Ы Visual Studio 2017 Добавлено через 36 секунд
0 |
Yetty 7427 / 5021 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
||||
21.01.2018, 16:41 |
11 |
|||
Yetty, Что вы предлагаете? Можете конкретно показать? примерно так:
переменную с не использовал (только вывод результата) — если она нужна сообщите
1 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 16:42 [ТС] |
12 |
Yetty, Спасибо, завтра попробую с этим. Сейчас времени уже нету) Если что, обращусь к вам.
0 |
139 / 67 / 46 Регистрация: 15.10.2015 Сообщений: 308 |
|
21.01.2018, 16:43 |
13 |
если я использую std::, не запускается Это еще что за магия?
0 |
Ilya-Glushko 0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
||||
21.01.2018, 16:43 [ТС] |
14 |
|||
Reavolt,
0 |
139 / 67 / 46 Регистрация: 15.10.2015 Сообщений: 308 |
|
21.01.2018, 16:44 |
15 |
Ilya-Glushko, Я имел в виду то, как программа может не работать с указыванием пространства имён?
0 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 16:46 [ТС] |
16 |
Reavolt, Сам задаюсь этим вопрос, штука в том, что при отсутсвии «using namespace std;» не запускается, а при присутствии и указании «std::» тоже выдает ошибку, даже на примерах из обучения.
0 |
139 / 67 / 46 Регистрация: 15.10.2015 Сообщений: 308 |
|
21.01.2018, 16:48 |
17 |
Ilya-Glushko, Если вы указываете пространство имен напрямую std::cout… то вам вообще не нужен using namespace std;
0 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 16:50 [ТС] |
18 |
Reavolt, Указыва и убирать using namespace std; пробовал, одно и тоже.
0 |
7427 / 5021 / 2891 Регистрация: 18.12.2017 Сообщений: 15,694 |
|
21.01.2018, 17:25 |
19 |
Ilya-Glushko, самостоятельно добавьте в калькулятор возможность сложения, вычитания и возведения в степень
1 |
0 / 0 / 0 Регистрация: 21.01.2018 Сообщений: 11 |
|
21.01.2018, 17:31 [ТС] |
20 |
Yetty, спасибо, попробую!
0 |
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Warning (level 1 and level 4) C4700 |
Compiler Warning (level 1 and level 4) C4700 |
08/30/2022 |
C4700 |
C4700 |
2da0deb4-77dd-4b05-98d3-b78d74ac4ca7 |
Compiler Warning (level 1 and level 4) C4700
uninitialized local variable ‘name‘ used
Remarks
The local variable name has been used, that is, read from, before it has been assigned a value. In C and C++, local variables aren’t initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.
To fix this issue, you can initialize local variables when they’re declared, or assign a value to them before they’re used. A function can be used to initialize a variable that’s passed as a reference parameter, or when its address is passed as a pointer parameter.
The /sdl
(Enable Additional Security Checks) compiler option elevates this warning to an error.
Example
This sample generates C4700 when variables t
, u
, and v
are used before they’re initialized, and shows the kind of garbage value that can result. Variables x
, y
, and z
don’t cause the warning, because they’re initialized before use:
// c4700.cpp // compile by using: cl /EHsc /W4 c4700.cpp #include <iostream> // function takes an int reference to initialize void initialize(int& i) { i = 21; } int main() { int s, t, u, v; // Danger, uninitialized variables s = t + u + v; // C4700: t, u, v used before initialization std::cout << "Value in s: " << s << std::endl; int w, x; // Danger, uninitialized variables initialize(x); // fix: call function to init x before use int y{10}; // fix: initialize y, z when declared int z{11}; // This C++11 syntax is recommended over int z = 11; w = x + y + z; // Okay, all values initialized before use std::cout << "Value in w: " << w << std::endl; }
When this code is run, t
, u
, and v
are uninitialized, and the output for s
is unpredictable:
Value in s: 37816963
Value in w: 42
When I compile this code it says «error C4700: uninitialized local variable ‘b’ used». I’m not sure what I have to do now to fix this problem. I’m neither an IT student or technican but I very like to learn C++ and I’m learning it by myself. I’ve been on this for 1 day.
Many thanks
#include <stdio.h>
#include <iostream>
//A.
//1--
void InputArray(int *a, int &n)
{
printf("Insert n = ");
scanf("%d", &n);
a = new int[n];
for (int i=0; i<n; i++)
{
printf("Enter the key's a[%d] values: ", i);
scanf("%d",&a[i]);
}
}
void main()
{
int *b, m;
InputArray(b, m);
}
bemeyer
6,2144 gold badges36 silver badges86 bronze badges
asked Feb 20, 2014 at 19:18
2
b
is passed by value, which means a copy will be made, but since it’s not initialized, you get the warning. Simply initialize it:
int *b = nullptr;
or
int *b = NULL;
answered Feb 20, 2014 at 19:21
Luchian GrigoreLuchian Grigore
253k64 gold badges457 silver badges621 bronze badges
0
If you want the function to modify the caller’s variable, then pass by reference:
void InputArray(int *&a, int &n)
^
Your version passes the uninitialised pointer by value; the function modifies a local copy of it, but leaves b
in its uninitialised state.
answered Feb 20, 2014 at 19:19
Mike SeymourMike Seymour
249k28 gold badges447 silver badges640 bronze badges
3
The pointers are not default initialized, so your variable b
is uninitialized, this is the source of error. You have to initialize this variable to fix this:
void main()
{
int *b = NULL, m;
InputArray(b, m);
}
After you fix this there is additional problem in your code. It seems from the way you call a function that you expect to persistently change pointer b
passed into it, so that b
will point into memory allocated with new
after function returned. But you pass a pointer by value what means changes made in function will not be reflected in original variable b
which will still point to what it pointed before the call to a function. (the array will be allocated inside function and will stay in memory after function returned but you will leak this memory as b
won’t point into it). To fix this you have to pass pointer by reference:
void InputArray(int*& a, int& n)
Also: where is delete
? Remember: mapping new
to delete
is bijection: every new
corresponds to single delete
placed somewhere in code.
answered Feb 20, 2014 at 19:22
4pie04pie0
29.1k9 gold badges82 silver badges118 bronze badges
2
First of all, did you learn how to use an pointer correctly ? because if you know how to use pointer u should know that when you declare a pointer you need to be initialized to NULL before you can use it, correct me if i’m wrong.
Example
int *b = nullptr;
int *b = NULL;
int *b = 0;
int *b(0);
It’s all the same thing but in an different way
answered Jan 2, 2017 at 17:41
1
I have a question related to my C/C++ code. I tried some researches but there was no specific answer for my problem. I hope you will response to my question as soon as possible.
Here is my full code in C language:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define M 500
#define N 500
int
main ()
{
//set number of threads here
//omp_set_num_threads(8);
int i, j, k;
double sum;
double **A, **B, **C;
A = malloc (M * sizeof (double *));
B = malloc (M * sizeof (double *));
C = malloc (M * sizeof (double *));
for (i = 0; i < M; i++)
{
A[i] = malloc (N * sizeof (double));
B[i] = malloc (N * sizeof (double));
C[i] = malloc (N * sizeof (double));
}
double start, end;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
A[i][j] = j * 1;
B[i][j] = i * j + 2;
C[i][j] = j - i * 2;
}
}
start = omp_get_wtime ();
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
sum = 0;
for (k = 0; k < M; k++)
{
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
end = omp_get_wtime ();
printf ("Time of computation: %fn", end - start);
cin.get ();
return 0;
}
The code terminates because of some bugs.
The result of the code is given here:
error C4700: uninitialized local variable 'A' used
error C4700: uninitialized local variable 'B' used
error C4700: uninitialized local variable 'C' used
Please consider my question
Best Regards.
Hristo Iliev
72.4k12 gold badges134 silver badges186 bronze badges
asked Jan 11, 2015 at 15:33
8
malloc() returns a void pointer, you have to cast it:
A = (double**) malloc (M * sizeof (double *));
B = (double**) malloc (M * sizeof (double *));
C = (double**) malloc (M * sizeof (double *));
for (i = 0; i < M; i++)
{
A[i] = (double*) malloc (N * sizeof (double));
B[i] = (double*) malloc (N * sizeof (double));
C[i] = (double*) malloc (N * sizeof (double));
}
if you are using c++ maybe is better to use «new» instead of malloc:
A = new double* [M];
B = new double* [M];
C = new double* [M];
for (i = 0; i < M; i++)
{
A[i] = new double[N];
B[i] = new double[N];
C[i] = new double[N];
}
answered Jan 11, 2015 at 21:11
Здравствуйте. Я совсем новичок в программировании, никакого опыта не было.
В общем компилятор показывает ошибку «error C4700: использована неинициализированная локальная переменная «a» и также «b».
Не могу понять, что нужно сделать, укажите пожалуйста на ошибку.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double a, b, sum, raz, umn, del;
sum = a + b;
raz = a - b;
umn = a*b;
del = a / b;
cout << "vvedite dannie n";
cin >> a, b;
if (a + b)
cout << sum << "n";
else
if (a - b)
cout << raz << "n";
else
if (a*b)
cout << umn << "n";
else
if (a / b)
cout << del << "n";
else
cout << "hernyu ne nesi, dyatel. n";
system("pause");
return 0;
}
-
Вопрос заданболее трёх лет назад
-
25031 просмотр
Вы складываете a и b, не присвоив им значений. В C/C++ в этом случае в переменных может оказаться произвольный мусор. Нужно писать double a = 0; double b = 0;
Дело в том, что ты выполняешь операции над переменными, которым не присвоено значение. Инициализируй их, например нулями
double a =0.0;
double b=0.0;
double sum, raz, umn, del;
double a, b, sum, raz, umn, del;
sum = a + b;
raz = a - b;
umn = a*b;
del = a / b;
Ты сразу суммируешь и делаешь прочие операции с переменными, которым не присвоено никакое значение. Перенеси все операции после cin и предупреждение пропадает.
А сразу походу система закрытия тегов отработала
Пригласить эксперта
Т.к. на вопрос уже ответили — разрешите пошутить старую шутку:
Подходит 2-х дневный программист к senior'у и показывает неработающую программу:
- Подскажите, пожалуйста, где у меня ошибка?
- В ДНК, - вздыхает senior.
(без обид, just for fun)
#include <iostream>
using namespace std;
int main()
{
double a, b, sum, raz, umn, del;
cout << "vvedite dannie n";
cin >> a;
cin >> b;
sum = a + b;
raz = a - b;
umn = a*b;
del = a / b;
if (a + b)
cout << sum << "n";
else
if (a - b)
cout << raz << "n";
else
if (a*b)
cout << umn << "n";
else
if (a / b)
cout << del << "n";
else
cout << "hernyu ne nesi, dyatel. n";
system("pause");
return 0;
}</iostream>
как вариант
Ещё неплохо бы добавить проверку на то чтобы b было не равно 0.
А то деление на ноль и всё такое. Ошибка может выскочить.
-
Показать ещё
Загружается…
24 июн. 2023, в 10:51
5000 руб./за проект
24 июн. 2023, в 10:40
10000 руб./за проект
24 июн. 2023, в 10:30
20000 руб./за проект