繁体   English   中英

cout 在我的程序上不能正常工作,有人可以帮助我吗?

[英]cout doesn't works properly on my program, can somebody help me?

在此处输入图像描述我在 C++ 中使用 STL,并且在 bucle 内,cout 无法正确打印浮点数。 我的程序将值广告给一个向量,然后将其传递给一个函数以查看条件是否存在,实际上它工作得很好,但只是 cout 不说话,我已经尝试过使用 printf() 但它给出了相同的结果。 注意:请算法给我反馈我的问题是我第一次做,英语不是我的母语

我的代码:

#include<bits/stdc++.h>
#include<vector>
using namespace std;
void isthereanumber(vector<float> array);
int main(){
    string ans;vector<float> array;float number;
    do{
        fflush(stdin);
        cout<<"insert a value for the vector: "<<endl;
        cin>>number;
        array.push_back(number);
        fflush(stdin);
        cout<<"would you like to keep adding values to the vector? "<<endl;
        getline(cin,ans);
    }while(ans.compare("yes")==0);
    isthereanumber(array);
    return 0;
}
void isthereanumber(vector<float> array){
    float suma =0;
    for(vector<float>::iterator i=array.begin();i!=array.end();i++){
        for(vector<float>::iterator j=array.begin();j!=array.end();j++){
            if(i!=j){
                suma = suma+array[*j];
            }
        }
        if(suma=array[*i]){
            cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
            cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
            return;
        }
    }
    cout<<"there is not a number with such a condition: ";
return;
}

我想你可能有几个问题......

在您的 for 循环中,您正在为向量创建迭代器,但不仅仅是取消引用它们以访问索引元素,您正在取消引用它们,然后将其用作同一向量的索引。

此外,您的最后一个 if 语句具有赋值 = 而不是比较 ==。

我相信这更接近您想要实现的目标(对不起,我没有时间编译和检查):

    for(vector<float>::iterator i=array.begin();i!=array.end();i++){
    for(vector<float>::iterator j=array.begin();j!=array.end();j++){
        if(i!=j){
            suma = suma+*j;
        }
    }
    if(suma==*i){
        cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
        cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
        return;
    }
}

正如 cleggus 所说,已经存在一些问题。 这些需要首先解决。 在那之后, suma一直在增长,这是一个逻辑错误。

给定输入 5,5,10,一旦我们测试 10,我们希望将 suma 再次设置为 0 以使其工作,但现在它会变成 30 之类的东西。 这可以通过在外循环内移动 suma 来解决。

输入 5,5,10 的工作示例: https ://godbolt.org/z/gHT6jg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM