我提供的这段代码有什么问题?

What's wrong in this code i provided?

本文关键字:代码 什么 问题 段代码      更新时间:2023-10-16
#include<iostream>     
#include<math.h>
using namespace std;
int main()    
{        
    int x[100];         
    float a,f,t;
    cout<<" Enter the amplitude:";
    cin>>a;
    cout<<"Enter frequency:";
    cin>>f;
    f=1.0/f;
    cout<<"Enter the time interval::";
    cin>>t;
    int i=0;        
    while(i<t)
    {
        x[i] = a * sin(2 * 3.14 * f * t); 
        cout<<x[i]<<"  ";
    }
    return 0;       
}

当我运行它时,我只是得到大量的输出值,都是一样的。例如,输入5, 79会得到连续输出:

4  4  4  4  4  4  4  4  4  4
4  4  4  4  4  4  4  4  4  4
4  4  4  4  4  4  4  4  4  4
4  4  4  4  4  4  4  4  4  4
4  4  4  4  4  4  4  4  4  4
4  4  4  4  4  4  4  4  4  4
:
and so on...

您既没有增加i也没有减少t,这意味着您的循环很可能是无限的:

while(i<t)
{
    x[i] = a * sin(2 * 3.14 * f * t); 
    cout<<x[i]<<"  ";
 }

根据你的需要,在循环体中应该有一个类似i++的东西。

您可能还会发现每个数组元素都被设置为相同的值,因为您在计算中使用的是t而不是i的某个函数。

你需要包含两个标题

#include <iostream>
#include <cmath>