Error invalid operands to binary expression float and float

I'm trying to validate the division residue. Here is my code: NSUInteger myNumber = 2; // list is a NSArray if ((arrayImg.count / ((float) imgPerPage)) % 1 >0) { // do something } but I get...

I’m trying to validate the division residue. Here is my code:

NSUInteger myNumber = 2;
//  list is a NSArray

if ((arrayImg.count / ((float) imgPerPage)) % 1 >0)
{
 // do something
}

but I get this error:

error: invalid operands to binary expression (‘float’ and ‘float’)

if I do this:

float result = (arrayImg.count / ((float) imgPerPage));

works just fine but I don’t understand why I use the %1 I get the error.

Any of you knows what is wrong with my code?

I’ll really appreciate your help

rmaddy's user avatar

rmaddy

312k42 gold badges525 silver badges567 bronze badges

asked Mar 21, 2014 at 23:06

user2924482's user avatar

user2924482user2924482

7,91221 gold badges85 silver badges163 bronze badges

2

You can only use the modulo operator (%) with integer operands, so convert your floating point expression back to an integer first. Also it looks like you’re trying to test for odd/even, so you need % 2, not % 1. So change:

if ((arrayImg.count / ((float) imgPerPage)) % 1 >0)

to:

if (((int)(arrayImg.count / (float) imgPerPage)) % 2 > 0)

answered Mar 21, 2014 at 23:14

Paul R's user avatar

3

I apologize if this question has been asked before. I looked around and was not able to find a solution, I am new to C.
I understand that I am not able to get a % from a float. How would I be able to capture the remainder of this math, if I am using 2 floats?

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>

/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/

int main (void)
{
  float change;
  int counter = 0;
  int division;
  //float rem;
  float quarter = 0.25;
  //float quarter = 0.25, dime = 0.10, nickel = 0.05, penny = 0.01;
  /* Prompt user for an amont of change*/
  do{
    printf("How much do we owe you in change? ");
    change = GetFloat();
  }
  while (change <= 0);
  if (change >= quarter)
  {
    division  = (change / quarter);
    counter += division;
    //change = (int)(change % quarter);
    printf("change: %.2fn", change);
    printf("counter: %dn ", counter);
  }

  return (0);
}

Jonathan Leffler's user avatar

asked May 26, 2016 at 8:20

Lucky500's user avatar

You may want to check
fmod.

You can also do something like change = change - (int)(change / quarter) * quarter

answered May 26, 2016 at 8:28

Gary Sham's user avatar

Gary ShamGary Sham

5034 silver badges10 bronze badges

1

You could implement the modulo yourself:

https://en.wikipedia.org/wiki/Modulo_operation

int a = (int)(change / quarter);
int mod = (int)(change - (quarter * a));

Also it might be possible to do it this way:

long mod = ((long)(change * 1000) % (long)(quater * 1000));

depending on the precision of your floats modify the 1000 and think about dividing the result by 1000!

But maybe it would be better to rethink what you really want as result?

vog's user avatar

vog

22.5k11 gold badges57 silver badges73 bronze badges

answered May 26, 2016 at 8:33

PowerStat's user avatar

PowerStatPowerStat

3,7397 gold badges32 silver badges55 bronze badges

Just scale up all your variable by 100 and then use integers instead of float.

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>

/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/

int main (void)
{
    float change_f;
    int change;
    int counter = 0;
    int division;
    //float rem;
    int quarter = 25;
    //int quarter = 25, dime = 10, nickel = 5, penny = 1;
    /* Prompt user for an amont of change*/
    do{
        printf("How much do we owe you in change? ");
        change_f = GetFloat();
    }
    while (change_f <= 0);
    change = (int)(change_f*100);
    if (change >= quarter)
    {
        division  = (change / quarter);
        counter += division;
        //change = (int)(change % quarter);
        printf("change: %.2fn", change_f);
        printf("counter: %dn ", counter);
    }

    return (0);
}

NOTE: Choose scale factor according to the input precision i.e if it is 3 decimal digits then choose 1000 and so on.

answered May 26, 2016 at 8:31

Nishant's user avatar

NishantNishant

2,5611 gold badge16 silver badges29 bronze badges

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    float matrix[7][7]={{1.3,15.4,7.8,13.7,10.1,2.5,17.4},
                        {12.3,7.5,6.3,11.4,18.5,14.9,8.2},
                        {7.3,11.2,4.4,10.8,8.9,17.2,18.4},
                        {15.8,17.5,4.8,9.8,7.1,12.6,11.7},
                        {5.3,13.6,13.2,19.2,16.4,2.7,1.8},
                        {9.5,0.7,1.9,14.3,0.2,5.4,3.1},
                        {0.8,19.9,6.7,12.7,2.6,4.9,11.5}};
    float max=matrix[0][0];
    float min=matrix[0][0];
    float sclproizv;
    int imax,jmin;
    for(int i=0;i<7;i++){
        for(int j=0;j<7;j++){
            printf("%.1ft", matrix[i][j]);
            if(matrix[i][j]>max)
            {
                max=matrix[i][j];
                imax=i;
 
            }
            if(matrix[i][j]<min)
            {
                min=matrix[i][j];
                jmin=j;
            }
            sclproizv=matrix[imax,j]*matrix[i,jmin];
        }
        printf("n");
    }
    printf("Scalyarnoe proizvedenie:%.1fn", sclproizv);
    return 0;
}
#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main (void) {
    printf ("Please enter the change owed:"); 
    float amount = GetFloat(); 

    if (amount < 0) {
        printf ("Please enter a positive integar for the change"); 
    }

    float amountInCents = round(amount * 100); 

    if (amountInCents > 25) {
     float Quater_Coins = amountInCents % 25;
     printf("Number of $0.25 coins used = %f", Quater_Coins); 
 }


}

I keep getting this error:

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow    greedy.c  -lcs50 -lm -o greedy
**greedy.c:16:41: error: invalid operands to binary expression ('float' and 'float')
float Quater_Coins = amountInCents % 25;
                     ~~~~~~~~~~~~~ ^ ~~** 1 error generated. make: *** [greedy] Error 1

Cliff B's user avatar

Cliff B

66.2k4 gold badges31 silver badges56 bronze badges

asked Feb 7, 2016 at 19:14

Mohammed Shayan Khan's user avatar

The % operator only works with integers, so you’ll want to convert your float to an integer. That’s kind of the purpose of round(), to round off the float so it can be applied to an int variable.

answered Feb 7, 2016 at 19:41

Fobok's user avatar

FobokFobok

829 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

How to fix invalid operands c errorThe invalid operands to binary expression C++ error might occur when a variable or object is considered a function. Moreover, you might get the same error due to using the wrong types of operands with the operators. If you are still in the same confused state, then read further to find a detailed explanation.

By the end of this post, you’ll surely figure out the erroneous line in your code, understand the reason, and have the perfect solution.

Contents

  • Why Do Invalid Operands To Binary Expression C++ Error Occur?
    • – Most Vexing Parse
    • – Using Modulus With Variables of Double Data Type
    • – Using a Comparison Operator With External Class Objects
    • – Using a Comparison Operator With Operands That Can’t Be Compared
  • How To Fix Error Invalid Operands?
    • – Remove the Parenthesis Following the Variable Name
    • – Cast the Modulus Operands To Int
    • – Round the Function Output and Cast It To Int
    • – Overload the Comparison Operator Outside the Class
    • – Fix the Operands To Eliminate Invalid Operands To Binary Expression C++ Error
  • FAQ
    • – What Does the Error “Invalid” Operands To Binary >> (Double and Int) Tells?
  • Conclusion

Why Do Invalid Operands To Binary Expression C++ Error Occur?

The above error might be occurring due to the most vexing parse that indicates the interpretation of an object as a function call. Moreover, the invalid operands or the external operands throw the same error. You can read below the complete descriptions of the reasons that have been stated earlier:

– Most Vexing Parse

The most vexing parse tells you that the variable declaration or object creation was considered a function call. Hence, you will get the above error when you use the same variable later in your program as an operand.

You can understand the scenario by imagining that you have declared a variable but accidentally placed a parenthesis in front of it. Next, you’ve coded to store the input inside the same and now, you are trying to print it. Here, you will get the above error because C++ grammar considered the variable declaration as a function call.

The coding block for the above scenario has been attached below:

#include <iostream>
using namespace std;
int main()
{
int age();
cout << “Please enter your age here: “;
cin >> age;
cin.ignore();
cout << “Your age is: “<< age <<“n”;
cin.get();
}

– Using Modulus With Variables of Double Data Type

As shown in the error statement itself, the invalid operands cause the stated error. The most common situation depicting the given reason is when the modulus “%” is used with the operands of double data type. Know that you can use only integers with the modulus.

– Using a Comparison Operator With External Class Objects

You might get the said error while comparing the properties of external class objects.

Here is the code that depicts the above scenario:

#include <iostream>
using namespace std;
class Plant{
public:
int height;
};
int main(){
Plant a, b;
a.height = 20;
b.height = 25;
if(a != b){
// do something
}
}

– Using a Comparison Operator With Operands That Can’t Be Compared

Another reason for the invalid operands error can be comparing the operands that can’t be compared. Here, you can imagine comparing a float variable with the void. It will definitely throw the same error.

You can fix the invalid operands error by implementing one of the solutions shared below as per the erroneous code found in your program:

– Remove the Parenthesis Following the Variable Name

So, if you have confused the C++ compiler regarding the variable and it has interpreted the same as a function, then remove the parenthesis following the variable name. It will solve the issue.

– Cast the Modulus Operands To Int

You can cast the modulus operands to int data type to make the above error go away. Similarly, casting the operands according to the operator requirement will help you every time when you face the same error.

– Round the Function Output and Cast It To Int

If your binary expression that uses the modulus contains the function output as an operand, then it would be a better idea to round the output. Next, you can convert the same into int to make the expression work.

– Overload the Comparison Operator Outside the Class

Pointing towards the error caused while comparing the external class objects’ properties, you can solve the same by overloading the given operator. It will ensure that the operator is already aware of the required class.

Please look at the code shown above that uses the Plant class and then see here to solve the issue:

#include <iostream>
using namespace std;
class Plant{
public:
int height;
};
static bool operator!=(const Plant& obj1, const Plant& obj2) {
return obj1.height != obj2.height;
}
int main(){
Plant a, b;
a.height = 20;
b.height = 25;
if(a != b){
cout << “The heights aren’t the same.” << endl;
}
}

– Fix the Operands To Eliminate Invalid Operands To Binary Expression C++ Error

Double-check the operands that you are comparing and change them accordingly to solve the error.

FAQ

You can find more information in this section.

– What Does the Error “Invalid” Operands To Binary >> (Double and Int) Tells?

The “invalid” operands to binary >> (double and int) error shows up to tell you that you are using the “>>” operator with operands of double data type. Remember that you can use “>>” with the values of integer data type only.

Conclusion

Fixing the stated error in your code isn’t a big deal after learning about the above solutions. Here is the simplified list of the solutions to let you see the fixing processes through the broader side:

  • You can fix the above error by removing any syntax errors that confuse the C++ compiler between variables and functions
  • Casting and changing the operands as per the operator requirement can help you fix the above error
  • Overloading the operators can help you in using external class objects in binary expressions

Invalid operands c errorCertainly, the said error revolves around the invalidity of the operands. You should simply be careful while using the same to avoid the error.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

G

The code of your question is an image processing algorithm called Masks values are coefficients and the filtration process is similar to a mathematical operation called In essence, the implementation of your Filtro Espacial is correct! Your code error is the time you read and record https://en.wikipedia.org/wiki/Netpbm_format#PGM_example .ppmNote that you are reading the image dimensions in an inverted way. You are changing the amount of rows with the amount of image columns.Follow a tested and commented code capable of applying a Filtro Espacial Gaussiano de Smooth in a format image .ppm: #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LINE_MAX_LEN (64)
/* Representa um pixel da imagem */
typedef struct pixel_s
{
unsigned char red;
unsigned char green;
unsigned char blue;
} pixel_t;
/* Representa uma imagem */
typedef struct image_s
{
pixel_t ** buf;
int ncols;
int nrows;
} image_t;
image_t * image_create( int ncols, int nrows )
{
int i = 0;
image_t * img = (image_t*) calloc( 1, sizeof(image_t) );

img-&gt;buf = (pixel_t**) calloc( nrows, sizeof(pixel_t*) );

for( i = 0; i &lt; nrows; i++ )
img-&gt;buf[i] = (pixel_t*) calloc( ncols, sizeof(pixel_t) );

img-&gt;ncols = ncols;
img-&gt;nrows = nrows;

return img;

}
void image_destroy( image_t * img )
{
int i = 0;
for( i = 0; i &lt; img-&gt;nrows; i++ )
free(img-&gt;buf[i]);

free(img-&gt;buf);
free(img);

}
pixel_t * image_read_pixel( image_t * img, int col, int row )
{
/* Nao permite leitura fora das fronteiras da imagem original */
if( col >= img->ncols ) col = img->ncols — 1;
if( row >= img->nrows ) row = img->nrows — 1;
if( col < 0 ) col = 0;
if( row < 0 ) row = 0;
return &amp;img-&gt;buf[row][col];

}
image_t * image_gaussian_smooth_filter( image_t * img )
{
int x, y, col, row, newpx;
pixel_t * px;
int sum, div;
int kernel[5][5] = {{ 2, 4, 5, 4, 2 },
{ 4, 9, 12, 9, 4 },
{ 5, 12, 15, 12, 5 },
{ 4, 9, 12, 9, 4 },
{ 2, 4, 5, 4, 2 }};

/* Debug */
printf( «Filtrando Imagem: tipo=P3; nrows=%d; ncols=%dn», img-&gt;nrows, img-&gt;ncols );

image_t * newimg = image_create( img-&gt;ncols, img-&gt;nrows );

for( row = 0; row &lt; img-&gt;nrows; row++ )
{
for( col = 0; col &lt; img-&gt;ncols; col++ )
{
sum = 0;
div = 0;

for( y = 0; y &lt; 5; y++ )
{
for( x = 0; x &lt; 5; x++ )
{
px = image_read_pixel( img, col + (x — 2), row + (y — 2) );
sum += ( px-&gt;red * kernel[y][x] );
div += kernel[y][x];
}
}

newpx = sum / div;

newimg-&gt;buf[row][col].red = newpx;
newimg-&gt;buf[row][col].green = newpx;
newimg-&gt;buf[row][col].blue = newpx;
}
}

return newimg;

}
int image_save( const char * file, image_t * img )
{
int col = 0;
int row = 0;
FILE * pf = fopen( file , «w» );

if(!pf)
return -1;

fprintf( pf, «P3n»);
fprintf( pf, «# Arquivo PPM de saidan»);
fprintf( pf, «%d %dn», img-&gt;ncols, img-&gt;nrows );
fprintf( pf, «255n» );

/* Debug */
printf( «Gravando Imagem: arquivo=%s; tipo=P3; nrows=%d; ncols=%d; componente=255n», file, img-&gt;nrows, img-&gt;ncols );

for( row = 0; row &lt; img-&gt;nrows; row++)
{
for( col = 0; col &lt; img-&gt;ncols; col++ )
{
fprintf( pf, «%un», img-&gt;buf[row][col].red );
fprintf( pf, «%un», img-&gt;buf[row][col].green );
fprintf( pf, «%un», img-&gt;buf[row][col].blue );
}
}

fclose(pf);

return 0;

}
image_t * image_load( const char * file )
{
int col = 0;
int row = 0;
char tipo[3];
char line[LINE_MAX_LEN];
int header_index = 0;
int componente = 0;
int nrows = 0;
int ncols = 0;
image_t * img = NULL;
FILE * pf = fopen( file, «r» );

if(!pf)
return NULL;

/* Carega o Header do Arquivo PPM */
while( fgets( line, LINE_MAX_LEN, pf ) )
{
if( header_index == 0 )
{
sscanf( line, «%s», tipo );
header_index++;
}
else if(header_index == 1 )
{
header_index++;
}
else if(header_index == 2 )
{
sscanf( line, «%d %d», &amp;ncols, &amp;nrows );
header_index++;
}
else if( header_index == 3 )
{
sscanf(line, «%d», &amp;componente);
break;
}
}

/* Debug */
printf( «Carregando Imagem: arquivo=%s; tipo=%s; nrows=%d; ncols=%d; componente=%dn», file, tipo, nrows, ncols, componente );

/* Verifica se o tipo do arquivo eh P3 */
if( tipo[0] != ‘P’ || tipo[1] != ‘3’)
{
fclose(pf);
return NULL;
}

/* Cria uma imagem em branco */
img = image_create( ncols, nrows );

/* Carrega imagem */
for( row = 0; row &lt; nrows; row++)
{
for( col = 0; col &lt; ncols; col++)
{
/* Componente Vermelho */
fgets(line, LINE_MAX_LEN, pf );
sscanf( line, «%hhu», &amp;img-&gt;buf[row][col].red );

/* Componente Verde */
fgets( line, LINE_MAX_LEN, pf );
sscanf( line, «%hhu», &amp;img-&gt;buf[row][col].green );

/* Componente Azul */
fgets( line, LINE_MAX_LEN, pf );
sscanf( line, «%hhu», &amp;img-&gt;buf[row][col].blue );
}
}

fclose(pf);

return img;

}
int main( void )
{
/* Carrega imagem a partir do arquivo */
image_t * original = image_load( «imagem_cinza.ppm» );
if(!original)
{
printf(«Erro ao carregar imagem PPM.n»);
return 1;
}

/* Aplica filtro */
image_t * filtered = image_gaussian_smooth_filter( original );

/* Grava imagem filtrada em arquivo */
int ret = image_save(«imagem_filtrada.ppm», filtered );

if(ret &lt; 0)
{
printf(«Erro ao salvar imagem PPM.n»);

/* Libera memoria ocupada pelas imagens */
image_destroy(filtered);
image_destroy(original);

return 1;
}

/* Libera memoria ocupada pelas imagens */
image_destroy(filtered);
image_destroy(original);

return 0;

}
Output:Carregando Imagem: arquivo=imagem_cinza.ppm; tipo=P3; nrows=480; ncols=610; componente=255
Filtrando Imagem: tipo=P3; nrows=480; ncols=610
Gravando Imagem: arquivo=imagem_filtrada.ppm; tipo=P3; nrows=480; ncols=610; componente=255
Original Image: Filtered image: References: http://dcm.ffclrp.usp.br/~murta/PIM/PIM_2.pdf http://www.facom.ufu.br/~backes/gsi058/Aula06-FiltragemEspacial.pdf http://www.coe.utah.edu/~cs4640/slides/Lecture5.pdf

If you are trying to run modulo / remainder operator like below, there are higher chances you might get an error as “error: invalid operands to binary” The solution for this error is as mentioned below.

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 11.00;
        int remainder = num % 3.0;

        if (remainder == 0) {
                printf("number is divisiblen");
        } else {
                printf("number is not divisible: Remainder = %dn", remainder);
        }
        return 0;
}
 $ gcc using_mod.c 
using_mod.c: In function ‘main’:
using_mod.c:5:22: error: invalid operands to binary % (have ‘float’ and ‘double’)
  int remainder = num % 3.0; 

Solution :

The remainder operator (otherwise known as the modulo operator) % is a binary operator (i.e., takes exactly 2 operands) and operates only on integer types (e.g., short, int, long, long long, etc).

Hence, we either need to change float to int, or typecast both the values before and after % operator. like

int remainder = (int)num % (int)3.0;

The complete working program will look like as below,

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 6.00;
        int remainder = (int)num % (int)3.0;

        if (remainder == 0) {
                printf("number is divisiblen");
        } else {
                printf("number is not divisible: Remainder = %dn", remainder);
        }
        return 0;
}

Ошибка Arc4random: «Недопустимые операнды для двоичного выражения («с плавающей запятой» и «с плавающей запятой»)»

Я хочу создать кнопку в произвольном месте в определенном представлении. Я искал и читал некоторые темы SO, но не смог найти решение своей проблемы.

Вот мой код:

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect buttonRect = button1.frame;
buttonRect.size = CGSizeMake(100, 100);
button1.frame = buttonRect;

[self.arr addObject:button1];

int r = ([button1 frame].size.width)/2;

int x = r + (arc4random() % (self.view.frame.size.width - button1.frame.size.width));
int y = r + (arc4random() % (self.view.frame.size.height - button1.frame.size.height));
//ERROR:Invalid operands to binary expression ('float' and 'float')

[button1 setCenter:CGPointMake(x, y)]; 

2 ответы

мод (%) не работает с поплавками.

int x = r + (arc4random() % (int)(self.view.frame.size.width - button1.frame.size.width));
int y = r + (arc4random() % (int)(self.view.frame.size.height - button1.frame.size.height));

В качестве дополнительного примечания arc4random() % … is не рекомендуется.

Вот предпочтительный метод:

int x = r + arc4random_uniform(self.view.frame.size.width - button1.frame.size.width);
int y = r + arc4random_uniform(self.view.frame.size.height - button1.frame.size.height);

ответ дан 22 авг.

попробуйте изменить

int x = r + (arc4random() % (self.view.frame.size.width - button1.frame.size.width));
int y = r + (arc4random() % (self.view.frame.size.height - button1.frame.size.height));

в

int x = r + (arc4random() % ((int)(self.view.frame.size.width - button1.frame.size.width)));
int y = r + (arc4random() % ((int)(self.view.frame.size.height - button1.frame.size.height)));

Вероятно, это выдает эту ошибку, потому что вы пытаетесь вычислить модуль, используя число с плавающей запятой в качестве параметра.

ответ дан 22 авг.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

ios
uibutton
arc4random

or задайте свой вопрос.

Не знаю, почему я получаю эту ошибку. Это похоже на то, как a*a обрабатывает a* как указатель (float* на float* — это то же самое, что float на float). По-видимому, проблема решается, когда я объявляю a в подклассах, но дело в том, что я хочу, чтобы мои подклассы автоматически получали это от моего родительского класса.

Еще одна вещь, когда я добавляю «float a;» для каждого подкласса, который может запускать программа. Я сделал это, чтобы проверить, будет ли это работать, но нет. Поплавок a не получает значения в setA. Я только что добавил cout << a; после a = b ;.

#include"Oblik.h"
#include<cmath>

using namespace std;

class Jednakostranicni : public GeometrijskaFigura{

    float P(){
        return (a*a*sqrt(3))/4; //12    13  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return a+a+a; //15  12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
    }
    
};

class Kvadrat : public GeometrijskaFigura{
    
    float P(){
        return a*a;//23 12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return a+a+a+a;//26 12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
    }
    
};

class Krug : public GeometrijskaFigura{
    
    float P(){
        return a*a*3.14;//34    12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return 2*a*3.14;//37    12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'int' and 'float*' to binary 'operator*'
    }
    
};

int main(){
    
    GeometrijskaFigura *f;
    int x;
    
    cin>>x;
    
    f->setA(x);
    
    f=new Jednakostranicni;
    cout<<"Jednakostranicni-P: "<<f->P()<<" O: "<<f->O()<<endl;
    f=new Kvadrat;
    cout<<"Kvadrat-P: "<<f->P()<<" O: "<<f->O()<<endl;
    f=new Krug;
    cout<<"Krug-P: "<<f->P()<<" O: "<<f->O()<<endl;
    
    
    
    return 1;
    
    
}

// this is Oblik.h file code
#include<iostream>

using namespace std;

class GeometrijskaFigura{
    protected: float a;
    public:
        
        void setA(float b){
         a=b;
        }
        
        virtual float P()=0;
        virtual float O()=0;
};

1 ответ

Лучший ответ

У вас неопределенное поведение, поскольку f не инициализирован:

GeometrijskaFigura *f;
int x;
    
std::cin >> x;
    
f->setA(x); // UB: use uninitialized f.

Должно быть

int a;

std::cin >> a;

Jednakostranicni j;
j.setA(a);
std::cout << "Jednakostranicni-P: " << a.P() << " O: " << a.O() << std::endl;

Kvadrat k;
k.setA(a);
std::cout << "Kvadrat-P: " << k.P() << " O: " << k.O() << std::endl;

Krug krug;
krug.setA(a);
std::cout << "Krug-P: " << krug.P() << " O: " << krug.O() << std::endl;


0

Jarod42
7 Дек 2020 в 10:12

Error: invalid operands of types 'int' and 'float*' to binary'operator/'
int *average = new int((num) / data);

показывая для этой строки кода.
Почему так?

float *data;
int num;
int mode;
double average, median;

cout << "How many students were surveyed?  ";
cin >> num;
data = makeArray(num);

float getAverage(float *data, int num)
{
int *average = new int((data) / num);
return *average;
}

1

Решение

Это означает, что вы сравниваете два несовместимых типа вместе. Один из num а также data является intа другой float*, В зависимости от поведения, которое вы хотите, вы захотите

  1. Разыменуйте указатель, как в *x для того, что x это указатель
    2а. Вы хотите разыграть int к float за floating point divisionгде результат преобразуется обратно в int
    2b. Вы хотите разыграть float для int, за integer division, который затем будет преобразован обратно в int,

Обновить
Поскольку вы обновили свой код, я укажу на большую проблему; у тебя сейчас утечка памяти.

Я бы посоветовал вам вместо этого возвратить ваше целое число по значению и, возможно, передать по ссылке или константе ссылки и избегать указателей целиком, но более того, я бы предложил некоторую симметрию в ваших входных параметрах, а также правильность констант:

//your code:
float getAverage( float *data, int sum )
{
//data is a float* and needs to be de-ref'd and casted to int for float but isnt
int *average = new int( (data) / num );
//note that now average is a pointer to a newly constructed int that will never be free'd
return *average;  //because you return it here, where the value will then be implicily converted to a float and be mostly worthless.
}

// In both suggestions I will use symmetric types, I will not introduce dynamic memory and I will use floating point division for maximal accuracy.

// Suggestion one use Const References
float getAverage( const float &data, const int &num)
{
float result = data / (float) num;
return result;
}

// Suggestion two use pointers to constants
float getAverage( const float *data, const int *num )
{
float result = (*data) / float(*num);
return result;
}

// Suggestion three pass by value since primitives are cheap
float getAverage( float data, int num)
{
float result = data / (float) num;
return result;
}

1

Другие решения

Других решений пока нет …

Понравилась статья? Поделить с друзьями:
  • Error invalid number of arguments for encryption
  • Error invalid new expression of abstract class type
  • Error invalid module instantiation
  • Error invalid method declaration return type required java
  • Error invalid mailbox перевод