有人可以帮我这个代码吗?我不知道为什么不工作? [英] Can someone please help me with this code? I don't know why it isn't working?

查看:68
本文介绍了有人可以帮我这个代码吗?我不知道为什么不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   iostream  >  
使用 命名空间标准;
/ *
* InflationRate - 根据新旧消费者物价指数计算通货膨胀率
* @param old_cpi:是一年前的消费者价格指数
* @param new_cpi:是当前的消费者价格指数
* @returns计算的通货膨胀率或0如果输入无效。
* /

void getCPIValues(float& old_cpi,float& new_cpi);

double InflationRate( float old_cpi, float new_cpi);

void swap_values(double& a,double& b);

void sort_array( double MAX_RATE [], int numRates);

double findMedian( double MAX_RATES [], int numRates);

const int MAX_RATES = 20 ;

int main() // C ++程序首先执行函数main
{
// # 1:为旧的消费者价格指数(cpi)和新的cpi
声明两个浮点变量 float old_cpi,new_cpi,infrt,sum = 0 ,avg;
再次 char ;
int crt = 0 ;
double array [MAX_RATES];
int numRates;

执行
{
// #2:读取cpi的两个浮点值并将它们存储在变量中
getCPIValues(old_cpi,new_cpi);

// #3:用两个cpis调用函数InflationRate
// #4:打印结果
infrt = InflationRate(old_cpi,new_cpi );
if (infrt!= 0
{
sum + = infrt; CRT ++;
}

cout<< 通货膨胀率为<< infrt<< ENDL;
for int i = 0 ; i< array [MAX_RATES]; i ++)
cin>> numRates;

// int numRates = sizeof(array)/ sizeof(MAX_RATES []);


// 奖金#1:将逻辑放入# 2-4循环中要求用户输入'y'如果有更多数据
cout<< 再试一次?(y或Y):;
cin>>再次;
} while ((再次== ' Y')||(再次== ' y'));

// 奖金#2:保持有效通胀率和数字的总计计算费率来计算平均费率。
// 在循环后打印结果
// 计算平均值
avg = sum / crt;
cout<< 平均费率为<< avg<< ENDL;

cout<< 中位数为<< findMedian(MAX_RATES [],numRates)<< ENDL;

return 0 ;
}

// 函数要求用户输入新旧消费者价格指数
// 检查数字是否大于0
void getCPIValues(float& old_cpi,float& new_cpi)
{
do
{
cout<< 输入旧的和新的消费者价格指数:;
cin>> old_cpi>> new_cpi;
if ((old_cpi< = 0 )||(new_cpi< = 0 ))
{
cout<< 错误:CPI值必须大于0.;
}
} while ((old_cpi< = 0 )||( new_cpi< = 0 ));
}

// double InflationRate(float old_cpi,float new_cpi)
// 前提条件:两个价格必须大于0.0
< span class =code-comment> //
后置条件:无效输入返回通货膨胀率为0
double InflationRate( float old_cpi, float new_cpi)
{
if ((old_cpi< = 0 )||(new_cpi< = < span class =code-digit> 0 )|| old_cpi == new_cpi)
{
return 0 ;
}
else
// 实施InflationRate以计算增加或减少的百分比
// 使用(new_cpi - old_cpi)/ old_cpi * 100
return ((new_cpi - old_cpi)/ old_cpi * 100 );
}


void swap_values(double& a,double& b)
{
double temp;
a = b;
b = temp;

}

void sort_array( double MAX_RATE [], int numRates)
{
int index_of_smallest;

for int i = 0 ; i< numRates - 1 ; i ++)
{
index_of_smallest = i;
for int j = i + 1; j< numRates; j ++)
{
if (MAX_RATES [j]< MAX_RATES [index_of_smallest])
{
index_of_smallest = j;
}
}
swap_values(& MAX_RATES [index_of_smallest],& MAX_RATES [i])
}
}

double findMedian( double MAX_RATES [], int numRates )
{
// 对数组进行排序
sort_array(MAX_RATES ,MAX_RATES + numRates);

// 检查偶数情况
if (numRates% 2 != 0
return double )MAX_RATES [numRates / 2];

return double )(MAX_RATES [(numRates- 1 )/ 2] + MAX_RATES [numRates / 2])/ 2. 0 ;
}





我的尝试:



错误:

在函数'int main()'中:
61:55:错误:在']'令牌之前预期的primary-expression
函数'void sort_array(double *,int)':
114:28:error:无效类型'const int [int]'对于数组下标
114:59:错误:无效类型'const int [int]'对于数组下标
119:49:错误:无效类型'const int [int]'对于数组下标
119:64:错误:无效类型'const int [int ]'for array下标
在函数'double findMedian(double *,int)'中:
126:35:错误:从'double *'无效转换为'int'[-fpermissive]
105:6:注意:初始化'void sort_array(double *,int)'的参数2

解决方案

希望这会对你有所帮助。



 #include< iostream> 
using namespace std;
/ *
* InflationRate - 根据新旧消费者价格指数计算通货膨胀率
* @param old_cpi:是一年前的消费者价格指数
* @param new_cpi:是当前的消费者价格指数
* @returns计算的通货膨胀率或0如果输入无效。
* /
void getCPIValues(float& old_cpi,float& new_cpi);

double InflationRate(float old_cpi,float new_cpi);

void swap_values(double& a,double& b);

void sort_array(double MAX_RATE [],int numRates);

double findMedian(double MAX_RATES [],int numRates);

const int MAX_RATES = 20;

int main()// C ++程序首先执行函数main
{
//#1:为旧的消费者价格指数(cpi)声明两个浮点变量新的cpi
浮动old_cpi,new_cpi,infrt,sum = 0,avg;再次
char;
int crt = 0;
double array [MAX_RATES];
int numRates;

do
{
//#2:读取cpi的两个浮点值并将它们存储在变量
getCPIValues(old_cpi,new_cpi);

//#3:用两个cpis调用函数InflationRate
//#4:打印结果
infrt = InflationRate(old_cpi,new_cpi);
if(infrt!= 0)
{
sum + = infrt; CRT ++;
}

cout<< 通货膨胀率是<< infrt<< ENDL;
for(int i = 0; i< array [MAX_RATES]; i ++)
cin>> numRates;

// int numRates = sizeof(array)/ sizeof(MAX_RATES []);


// BONUS#1:将#2-4中的逻辑置于循环中,如果有更多数据,则要求用户输入'y'
cout<< ; 再试一次?(y或Y):;
cin>>再次;
} while((再次=='Y')||(再次=='y'));

//奖金#2:保持有效通货膨胀率和计算费率的总和,以计算平均费率。
//在循环后打印结果
//计算平均值
avg = sum / crt;
cout<< 平均速率是<< avg<< ENDL;

cout<< 中值率是<< findMedian(array,numRates)<< ENDL;

返回0;
}

//函数要求用户输入旧的和新的消费者价格指数
//检查数字是否大于0
void getCPIValues(float& ; old_cpi,float& new_cpi)
{
do
{
cout<< 输入旧的和新的消费者价格指数:;
cin>> old_cpi>> new_cpi;
if((old_cpi< = 0)||(new_cpi< = 0))
{
cout<< 错误:CPI值必须大于0。
}
} while((old_cpi< = 0)||(new_cpi< = 0));
}

// double InflationRate(float old_cpi,float new_cpi)
//前提条件:两个价格必须大于0.0
//后置条件:通货膨胀率返回或0表示无效输入
double InflationRate(float old_cpi,float new_cpi)
{
if((old_cpi< = 0)||(new_cpi< = 0)|| old_cpi == new_cpi)
{
返回0;
}
其他
//实施InflationRate计算增加或减少百分比
//使用(new_cpi - old_cpi)/ old_cpi * 100
返回((new_cpi - old_cpi)/ old_cpi * 100);
}


void swap_values(double& a,double& b)
{
double temp = 0.0f;
a = b;
b = temp;

}

void sort_array(double MAX_RATE [],int numRates)
{
int index_of_smallest;

for(int i = 0; i< numRates - 1; i ++)
{
index_of_smallest = i;
for(int j = i + 1; j< numRates; j ++)
{
if(MAX_RATE [j]< MAX_RATE [index_of_smallest])
{
index_of_smallest = j;
}
}
swap_values(MAX_RATE [index_of_smallest],MAX_RATE [i]);
}
}

double findMedian(double MAX_RATE [],int numRates)
{
//排序数组
sort_array(MAX_RATE ,MAX_RATES + numRates);

//检查偶数情况
if(numRates%2!= 0)
return(double)MAX_RATE [numRates / 2];

return(double)(MAX_RATE [(numRates - 1)/ 2] + MAX_RATE [numRates / 2])/ 2.0;
}


查看错误消息:

 61:55:错误:']'令牌之前的预期主要表达式



第61行,第55栏 - 它在结束方括号之前需要一些东西。

我'我猜这是这一行:

 cout<< 中值率是<< findMedian(MAX_RATES [],numRates)<< endl; 



 MAX_RATES [] 

需要[和]之间的索引值数组索引指示符..



对其他消息执行相同操作 - 它们都为您提供行号和列号,因此请使用IDE或编辑器准确查找他们指的是哪一行和一列。这应该会让你知道你输错了什么!


引用:

有人可以请帮助我用这个代码?我不知道它为什么不起作用?



学会自救!编译器为您提供了大量的提示,学会使用它们。

Quote:

在函数'int main()':

61 55 :错误:在']之前预期的primary-expression '令牌



在功能 main() 61 位置 55

 cout<<  中位数为<< findMedian(MAX_RATES  [] ,numRates)<< ENDL; 
^ char



编译器不喜欢它。

- 检查你在做什么。 ' [] '用于数组。

- 什么是 MAX_RATES

  const   int  MAX_RATES =  20 ; 



MAX_RATES 是一个全局常量,而不是数组,编译器不明白你尝试做什么。

Nota:至少作为初学者,在本地和全局定义的混合中使用相同的名称总是一个坏主意。



< blockquote class =quote>

Quote:

114:28:错误:无效类型'const int [int]'对于数组下标

114:59 :错误:数组下标的无效类型'const int [int]'



 如果 (MAX_RATES [j]< MAX_RATES [index_of_smallest])



这里再次使用像数组一样的整数常量。


#include <iostream>
using namespace std;
/*
 * InflationRate - calculates the inflation rate given the old and new consumer price index
 * @param old_cpi: is the consumer price index that it was a year ago
 * @param new_cpi: is the consumer price index that it is currently 
 * @returns the computed inflation rate or 0 if inputs are invalid.
 */
void getCPIValues(float& old_cpi, float& new_cpi);
 
double InflationRate(float old_cpi, float new_cpi);

void swap_values(double& a, double& b);

void sort_array (double MAX_RATE[], int numRates);

double findMedian(double MAX_RATES[], int numRates);

const int MAX_RATES = 20;

int main()   //C++ programs start by executing the function main
{
   // #1: declare two float variables for the old consumer price index (cpi) and the new cpi
   float old_cpi, new_cpi, infrt, sum = 0, avg;
   char again;
   int crt = 0;
   double array[MAX_RATES];
   int numRates;

   do 
   {
       // #2: Read in two float values for the cpi and store them in the variables
        getCPIValues(old_cpi, new_cpi);
        
       // #3: call the function InflationRate with the two cpis
       // #4: print the results
        infrt = InflationRate(old_cpi, new_cpi);
        if (infrt != 0)
        {
          sum += infrt; crt++;
        }
        
        cout << "Inflation rate is " << infrt << endl;
        for (int i = 0; i < array[MAX_RATES]; i++)
            cin >> numRates;
            
        //int numRates = sizeof(array)/sizeof(MAX_RATES[]);
        
        
        // BONUS #1: Put the logic in #2-4 in a loop that asks the user to enter 'y' if there's more data
        cout << "Try again? (y or Y): ";
        cin >> again;
    } while((again == 'Y') || (again == 'y'));
    
    // BONUS #2: Keep a running total of the valid inflation rates and the number of computed rates to calculate the average rate.
    // Print the results after the loop
    // calculate average 
    avg = sum/crt;
    cout << "Average rate is " << avg << endl;
    
    cout << "Median rate is " << findMedian(MAX_RATES[], numRates) << endl;

   return 0;
}

// function ask the user to input the old and new consumer price indices
// check if the numbers are greater than 0 
void getCPIValues (float& old_cpi, float& new_cpi)
{
    do
    {
        cout << "Enter the old and new consumer price indices: ";
        cin  >> old_cpi >> new_cpi;
        if((old_cpi <= 0) || (new_cpi <= 0))
        {
            cout << "Error: CPI values must be greater than 0.";
        }
    } while ((old_cpi <= 0) || (new_cpi <= 0));
}

// double InflationRate(float old_cpi, float new_cpi)
// precondition:   both prices must be greater than 0.0
// postcondition:  the inflation rate is returned or 0 for invalid inputs
double InflationRate(float old_cpi, float new_cpi)
{
    if ((old_cpi <= 0) || (new_cpi <= 0) || old_cpi == new_cpi) 
    {
       return 0;
    }
    else
   // Implement InflationRate to calculate the percentage increase or decrease
   // Use (new_cpi - old_cpi) / old_cpi * 100
       return ((new_cpi - old_cpi) / old_cpi * 100);
}


void swap_values(double& a, double& b)
{
    double temp;
    a = b;
    b = temp;
    
}

void sort_array (double MAX_RATE[], int numRates)
{
    int index_of_smallest;
    
    for (int i = 0; i < numRates -1; i++)
    {
        index_of_smallest = i;
        for (int j = i+1; j < numRates; j++)
        {
            if (MAX_RATES[j] < MAX_RATES[index_of_smallest])
            {
                index_of_smallest = j;
            }
        }
        swap_values(&MAX_RATES[index_of_smallest], &MAX_RATES[i])
    }  
}

double findMedian(double MAX_RATES[], int numRates)
{
    // sort the array
   sort_array(MAX_RATES, MAX_RATES+numRates);
 
    // check for even case
    if (numRates % 2 != 0)
       return (double)MAX_RATES[numRates/2];
     
    return (double)(MAX_RATES[(numRates-1)/2] + MAX_RATES[numRates/2])/2.0;
}



What I have tried:

Error:

 In function 'int main()':
61:55: error: expected primary-expression before ']' token
 In function 'void sort_array(double*, int)':
114:28: error: invalid types 'const int[int]' for array subscript
114:59: error: invalid types 'const int[int]' for array subscript
119:49: error: invalid types 'const int[int]' for array subscript
119:64: error: invalid types 'const int[int]' for array subscript
 In function 'double findMedian(double*, int)':
126:35: error: invalid conversion from 'double*' to 'int' [-fpermissive]
105:6: note: initializing argument 2 of 'void sort_array(double*, int)'

解决方案

Hope this will help you.

#include <iostream>
using namespace std;
/*
* InflationRate - calculates the inflation rate given the old and new consumer price index
* @param old_cpi: is the consumer price index that it was a year ago
* @param new_cpi: is the consumer price index that it is currently
* @returns the computed inflation rate or 0 if inputs are invalid.
*/
void getCPIValues(float& old_cpi, float& new_cpi);

double InflationRate(float old_cpi, float new_cpi);

void swap_values(double& a, double& b);

void sort_array(double MAX_RATE[], int numRates);

double findMedian(double MAX_RATES[], int numRates);

const int MAX_RATES = 20;

int main()   //C++ programs start by executing the function main
{
	// #1: declare two float variables for the old consumer price index (cpi) and the new cpi
	float old_cpi, new_cpi, infrt, sum = 0, avg;
	char again;
	int crt = 0;
	double array[MAX_RATES];
	int numRates;

	do
	{
		// #2: Read in two float values for the cpi and store them in the variables
		getCPIValues(old_cpi, new_cpi);

		// #3: call the function InflationRate with the two cpis
		// #4: print the results
		infrt = InflationRate(old_cpi, new_cpi);
		if (infrt != 0)
		{
			sum += infrt; crt++;
		}

		cout << "Inflation rate is " << infrt << endl;
		for (int i = 0; i < array[MAX_RATES]; i++)
			cin >> numRates;

		//int numRates = sizeof(array)/sizeof(MAX_RATES[]);


		// BONUS #1: Put the logic in #2-4 in a loop that asks the user to enter 'y' if there's more data
		cout << "Try again? (y or Y): ";
		cin >> again;
	} while ((again == 'Y') || (again == 'y'));

	// BONUS #2: Keep a running total of the valid inflation rates and the number of computed rates to calculate the average rate.
	// Print the results after the loop
	// calculate average 
	avg = sum / crt;
	cout << "Average rate is " << avg << endl;

	cout << "Median rate is " << findMedian(array, numRates) << endl;

	return 0;
}

// function ask the user to input the old and new consumer price indices
// check if the numbers are greater than 0 
void getCPIValues(float& old_cpi, float& new_cpi)
{
	do
	{
		cout << "Enter the old and new consumer price indices: ";
		cin >> old_cpi >> new_cpi;
		if ((old_cpi <= 0) || (new_cpi <= 0))
		{
			cout << "Error: CPI values must be greater than 0.";
		}
	} while ((old_cpi <= 0) || (new_cpi <= 0));
}

// double InflationRate(float old_cpi, float new_cpi)
// precondition:   both prices must be greater than 0.0
// postcondition:  the inflation rate is returned or 0 for invalid inputs
double InflationRate(float old_cpi, float new_cpi)
{
	if ((old_cpi <= 0) || (new_cpi <= 0) || old_cpi == new_cpi)
	{
		return 0;
	}
	else
		// Implement InflationRate to calculate the percentage increase or decrease
		// Use (new_cpi - old_cpi) / old_cpi * 100
		return ((new_cpi - old_cpi) / old_cpi * 100);
}


void swap_values(double& a, double& b)
{
	double temp = 0.0f;
	a = b;
	b = temp;

}

void sort_array(double MAX_RATE[], int numRates)
{
	int index_of_smallest;

	for (int i = 0; i < numRates - 1; i++)
	{
		index_of_smallest = i;
		for (int j = i + 1; j < numRates; j++)
		{
			if (MAX_RATE[j] < MAX_RATE[index_of_smallest])
			{
				index_of_smallest = j;
			}
		}
		swap_values(MAX_RATE[index_of_smallest], MAX_RATE[i]);
	}
}

double findMedian(double MAX_RATE[], int numRates)
{
	// sort the array
	sort_array(MAX_RATE, MAX_RATES + numRates);

	// check for even case
	if (numRates % 2 != 0)
		return (double)MAX_RATE[numRates / 2];

	return (double)(MAX_RATE[(numRates - 1) / 2] + MAX_RATE[numRates / 2]) / 2.0;
}


Look at the error message:

61:55: error: expected primary-expression before ']' token


Line 61, column 55 - it expects something before the closing square bracket.
I'm guessing that it's this line:

cout << "Median rate is " << findMedian(MAX_RATES[], numRates) << endl;


And the

MAX_RATES[]

needs an index value between the "[" and "]" array index indicators..

Do the same thing with the other messages - they all give you a line and column number, so use your IDE or editor to find out exactly which line and column they are referring to. That should give you a good idea what you typed wrong!


Quote:

Can someone please help me with this code? I don't know why it isn't working?


Learn to help yourself ! The compiler gives you tons of hints, learn to use them.

Quote:

In function 'int main()':
61:55: error: expected primary-expression before ']' token


In function main() line 61 position 55

cout << "Median rate is " << findMedian(MAX_RATES[], numRates) << endl;
                                                  ^ this char


The compiler don't like it.
- Check what you are doing. '[]' is used with arrays.
- What is MAX_RATES ?

const int MAX_RATES = 20;


MAX_RATES is a global constant, not an array, the compiler don't understand what you try to do.
Nota: It is always a bad idea to use the same name for many things with a mixing of local and global defines, at least as a beginner.

Quote:

114:28: error: invalid types 'const int[int]' for array subscript
114:59: error: invalid types 'const int[int]' for array subscript


if (MAX_RATES[j] < MAX_RATES[index_of_smallest])


Here again, you use the integer constant like an array.


这篇关于有人可以帮我这个代码吗?我不知道为什么不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆