c++ 从动态数组中阅读无效数据,可能是逻辑问题,但我没有看到

wpx232ag  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(131)

请帮忙,谢谢你的时间
任务是:创建动态数组,在其中输入数据,并使用数据进行计算。
错误位于第二个“for”循环的条件声明行。错误代码:“С6385”,错误文本:“阅读无效数据”

#include <iostream>
using namespace std;
double s, u, h;
int i = 0;
s = 0;

int main(){
    int ar_size;
    cout << "Enter array size" << endl;
    cin >> ar_size;
    int* a = new int[ar_size];
    
    for (int i = 0; i < ar_size; i++) {
        cout << "Enter array data" << endl;
        cin >> a[i];
        cout << "Value of " << i << " element is " << a[i] << endl; //check data
            for (i = 0; a[i] > 0 && a[i] < 3.14; i++) { //problem here, error code:"С6385", error text:"reading invalid data"
             u = 2 * cos(a[i]);
                h = 1 - 2 * sin(a[i]);
                s = s + u / h;
                cout << "When i = " << i << "\t" << "s = " << s << endl;
            }
    }
}
4ioopgfo

4ioopgfo1#

我把它改成了double,因为这看起来更像你的应用程序,但是你必须有很多i,需要一个if块,而不是一个for循环。希望这有帮助

#include<iostream>
#include<cmath>

using namespace std;

double u, h, s = {};

int main()
{
    int ar_size;
    cout << "Enter array size" << endl;
    cin >> ar_size;
    double* a = new double[ar_size];
    cin.clear();
    cin.ignore();
    
    for (int i = 0; i < ar_size; i++)
    {
        cout << "Enter array data" << endl;
        string input;
        getline(cin, input);
        a[i] = stod(input);
        cout << "Value of " << i << " element is " << a[i] << endl;
            if(a[i] > 0 && a[i] < 3.14)
            {
                u = 2 * cos(a[i]);
                h = 1 - 2 * sin(a[i]);
                s = s + u / h;
                cout << "When i = " << a[i] << "\t" << "s = " << s << endl;
            }
            else
            {
                cout << "out of bounds\n";
            }
    }
}

相关问题