Why does this code not work? My IDE is Visual Studio 2013.
#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit: ");
scanf ("%d", &convertTemp);
if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f and Celsius = %fn", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius); // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheitnn");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius); // and here
}
return (0);
}
float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}
The goal here is to add to the converting temperature project I did earlier and add an if else
statement function to it that comments on the temp. The error I get is
Error 3 error C2078: too many initializes
on both the lines where I call my function. I searched for an answer but couldn’t find any.
asked Feb 13, 2015 at 7:11
4
This line looks like an attempt at a C++ initialization of a float
with one too many arguments (hence the «too many initializers» error), not like a function call.
float tempatureGuide(fahrenheit, celsius);
Presumably you want to call the function and store the result in a variable:
float temp = tempatureGuide(fahrenheit, celsius);
Or just call the function and ignore the return value:
tempatureGuide(fahrenheit, celsius);
Especially since your function always returns 0
, so one might question the need for a non-void return type.
answered Feb 13, 2015 at 7:13
juanchopanzajuanchopanza
221k33 gold badges398 silver badges474 bronze badges
1
You need to call a function
float tempatureGuide(float fahrenheit, float celsius) { //...}
as
float retval = tempatureGuide(fahrenheit, celsius);
or least
tempatureGuide(fahrenheit, celsius); // not need to use return value
Only.
Sourav Ghosh
132k16 gold badges184 silver badges258 bronze badges
answered Feb 13, 2015 at 7:16
VagishVagish
2,50018 silver badges32 bronze badges
2
That is just a simple error. Please change 2 lines of code where you are calling tempatureGuide(fahrenheit, celsius); function as follows.
float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);
I tested the same in my VS2013 as you are using the same with the mentioned changes. I am able to compile and run it successfully. See the attachment.
answered Feb 13, 2015 at 7:23
Shivaraj BhatShivaraj Bhat
8332 gold badges9 silver badges20 bronze badges
3
Just call the function and return it to a variable of the same type.
answered Aug 24, 2021 at 15:50
1
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2078 |
Compiler Error C2078 |
11/04/2016 |
C2078 |
C2078 |
9bead850-4123-46cf-a634-5c77ba974b2b |
Compiler Error C2078
too many initializers
The number of initializers exceeds the number of objects to be initialized.
The compiler can deduce the correct assignment of initializers to objects and inner objects when inner braces are elided from the initializer list. Complete bracing also eliminates ambiguity and results in correct assignment. Partial bracing can cause C2078 because of ambiguity in the assignment of initializers to objects.
The following sample generates C2078 and shows how to fix it:
// C2078.cpp // Compile by using: cl /c /W4 C2078.cpp struct S { struct { int x, y; } z[2]; }; int main() { int d[2] = {1, 2, 3}; // C2078 int e[2] = {1, 2}; // OK char a[] = {"a", "b"}; // C2078 char *b[] = {"a", "b"}; // OK char c[] = {'a', 'b'}; // OK S s1{1, 2, 3, 4}; // OK S s2{{1, 2}, {3, 4}}; // C2078 S s3{{1, 2, 3, 4}}; // OK S s4{{{1, 2}, {3, 4}}}; // OK }
I’m using VS2013.
I can initialize an «array of strings» like this without any problems:
char titles[4][80] = { "Dad", "Idiot", "Donut Lover", "Fewl" }; // OK!
I have a struct declared like this:
typedef struct { char name[80]; char titles[4][80]; } Dude;
When I try to initialize the struct like this:
Dude homer = { .name = "Homer", .titles = { "Dad", "Idiot", "Donut Lover", "Fewl" } // error? };
I get an «error C2078: too many initializers». This is because of the array initialization- If I remove the
.titles = { "Dad", "Idiot", "Donut Lover", "Fewl" }
line, but leave the
.name = "Homer"
line, the error goes away. This means to me that designated initializers are at least partially implemented in VS.
Why am I getting this error?
If I change the declaration of the struct to look like this
typedef struct { char name[80]; char *titles[4]; } Dude;
the error goes away. This is, however, not a change I can make. Other parts of the code base require that the size of this struct is exactly 400 bytes.
Further, I’m quite aware that I could use strcpy to fill in each field, but that does not answer my question. I also realize I could initialize the struct without using designated initializers, but again that is not my question.
Почему этот код не работает? Моя IDE — это Visual Studio 2013.
#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit: ");
scanf ("%d", &convertTemp);
if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f and Celsius = %fn", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius); // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheitnn");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius); // and here
}
return (0);
}
float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}
Цель состоит в том, чтобы добавить к проекту преобразования температуры, который я делал ранее, и добавить if else
Функция заявления к нему, что комментирует темп. Я получаю ошибку
Error 3 error C2078: too many initializes
на обеих линиях, где я вызываю свою функцию. Я искал ответ, но не мог найти.
0
Решение
Эта строка выглядит как попытка инициализации C ++ float
с одним слишком много аргументов (следовательно, «слишком много инициализаторов«ошибка), а не как вызов функции.
float tempatureGuide(fahrenheit, celsius);
Предположительно, вы хотите вызвать функцию и сохранить результат в переменной:
float temp = tempatureGuide(fahrenheit, celsius);
Или просто вызовите функцию и проигнорируйте возвращаемое значение:
tempatureGuide(fahrenheit, celsius);
Тем более что ваша функция всегда возвращает 0
Таким образом, можно задаться вопросом о необходимости не пустого типа возврата.
3
Другие решения
Вам нужно вызвать функцию
float tempatureGuide(float fahrenheit, float celsius) { //...}
как
float retval = tempatureGuide(fahrenheit, celsius);
или хотя бы
tempatureGuide(fahrenheit, celsius); // not need to use return value
Только.
1
Это просто простая ошибка. Пожалуйста, измените 2 строки кода, где вы вызываете tempatureGuide (по Фаренгейту, Цельсию); функционировать следующим образом.
float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);
Я протестировал то же самое в моем VS2013, так как вы используете то же самое с упомянутыми изменениями. Я могу скомпилировать и запустить его успешно. Смотрите вложение.
0
- Forum
- General C++ Programming
- error C2078: too many initializers
error C2078: too many initializers
I want to change this to use user defined functions working on the first and i get this error, not sure how to fix it.
|
|
|
|
error C2061: syntax error : identifier ‘biggestNumber’
is the only error i got now if anyone can help fix that
Line 48: No () around the if condition.
Lines 73-76: Function definition inside another function. The definition itself would be wrong even if this wasn’t so. Badly formed parameter list. Missing function body.
Reread your source material on functions.
Last edited on
i fixed it now
|
|
*Never* but the else statement in the same line as the if statement. It makes code much harder to read.
In fact, it’s not recommendable to put the block in the same line as the statement.
There’s an extra semicolon on line 83.
Last edited on
Topic archived. No new replies allowed.
Фантомас 1 / 1 / 0 Регистрация: 12.02.2013 Сообщений: 18 |
||||
1 |
||||
13.02.2013, 13:37. Показов 7316. Ответов 4 Метки нет (Все метки)
Создаю текстовый массив. Выдает ошибку «error C2078: слишком много инициализаторов». При создании Int массива все нормально, а при создании екстового валит ошибку ( error C2078: слишком много инициализаторов ):
Что я наделал?)
__________________
0 |
Issues 433 / 368 / 149 Регистрация: 06.08.2012 Сообщений: 961 |
||||
13.02.2013, 13:40 |
2 |
|||
1 |
1 / 1 / 0 Регистрация: 12.02.2013 Сообщений: 18 |
|
13.02.2013, 13:45 [ТС] |
3 |
КАК, БЛИН? О_о
0 |
3985 / 3255 / 909 Регистрация: 25.03.2012 Сообщений: 12,102 Записей в блоге: 1 |
|
13.02.2013, 13:49 |
4 |
что не ясно?
1 |
1 / 1 / 0 Регистрация: 12.02.2013 Сообщений: 18 |
|
13.02.2013, 16:37 [ТС] |
5 |
Та ясно, просто после детального изучения рнр строгий синтаксис смотрится устарашающе….
1 |
That’s because there are too many initializers
You are specifying the array as 5×4, yet you have initializers 20×2
Either use static DWORD 2DArray[20][2] =
or change the initializer like so:
static DWORD 2DArray[5][4] = { { 0 , 1 , 2 , 3 } { 1 , 1 , 2 , 3 } { 2 , 1 , 2 , 3 } { 3 , 1 , 2 , 3 } { 4 , 1 , 2 , 3 } }
EDIT: Perhaps you meant:
static DWORD 3DArray[4][5][2] = { { { 0 , 1 }, { 1 , 4 }, { 2 , 5 }, { 3 , 6 }, { 4 , 25 } }, { { 0 , 2 }, { 1 , 9 }, { 2 , 10}, { 3 , 11}, { 4 , 26 } }, { { 0 , 3 }, { 1 , 13}, { 2 , 14}, { 3 , 15}, { 4 , 23 } }, { { 0 , 4 }, { 1 , 17}, { 2 , 18}, { 3 , 19}, { 4 , 22 } } }
You don’t need the first digit if these are the real numbers as they relate to the index anyway.
I would suggest:
static DWORD 3DArray[4][5] = { { 1, 4, 5, 6, 25 }, { 2 , 9 , 10 , 11 , 26 }, { 3 , 13 , 14 , 15 , 23 }, { 4 , 17 , 18 , 19 , 22 } }