【问题标题】:Multiply only negative numbers and output only negative integers from a file in C仅将负数相乘并仅从 C 中的文件中输出负整数
【发布时间】:2014-11-09 17:24:38
【问题描述】:

我需要将文件中的负数与内容相乘:12 7 -14 3 -8 10。所以我需要-14 乘以-8。 这是我的完整代码:

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

int main()
{
FILE *in, *out;
int x, negative, product;
in=fopen("C:\\Users\\emachines\\Desktop\\ind\\in.txt", "r");
if(in==NULL) //If file failed to open
{
printf ("Cannot open the file. Exiting...");
return -1;
}

printf("Numbers are:"); //Output integers
while(fscanf(in, "%d", &x)==1)
{
printf("%d ", x); //end of outputting integers
}

printf("\nNegative numbers are:"); //Output negative numbers
while(!feof(in)) 
{
fscanf(in, "%d", &negative);
while(negative<0)
{
printf("%d", negative); //end of outputting negative numbers
                        //multiply negative numbers
printf("mupltipying... Product - %d", product)
}
}

fclose(in);
return(0); //main returns int
}

那么如何只乘负数呢?如果我使用 x 变量输出 all 数字,如何输出 only negative 数字? 对不起我的英语

【问题讨论】:

  • 请正确格式化您的代码以使其可读。

标签: c file while-loop output scanf


【解决方案1】:

在打印数字时检查是否小于0打印它,同时制作这个数字的产品。这是你的工作代码。

#include <stdio.h>

int main()
{
FILE *in, *out;
int x, negative, product=1;
in=fopen("a.txt", "r");
if(in==NULL) //If file failed to open
{
printf ("Cannot open the file. Exiting...");
return -1; 
}
printf("Negative Numbers are:"); //Output integers
while(fscanf(in, "%d", &x)==1)
{
    if(x<0){
        product*=x;
        printf("%d ", x); //end of outputting integers
    }
}

printf("\n");
                        //multiply negative numbers
printf("mupltipying...\n Product=%d\n", product);
//printf("%d\n",product );


fclose(in);
return(0); //main returns int
}

【讨论】:

  • 我使用 a.txt 只是为了调试您的代码。您可以更改它。 :)
  • 谢谢。我尝试将那部分代码与另一部分代码一起使用,它输出所有整数。现在我明白为什么它不起作用了。 printf("Negative Numbers are:"); //Output negative integers while(fscanf(in, "%d", &amp;x)==1) { if(x&lt;0){ product*=x; printf("%d ", x); //end of outputting negative integers } } printf("\nProduct=%d", product); 但是为什么我不能同时输出我所有的整数,然后只输出负整数,然后乘负整数呢?
  • 你也可以这样做。您需要做的就是重新读取文件并打印所有数字,或者将数字存储在数组中然后再打印。
【解决方案2】:

您只需要一个循环,其中必须包含 if 语句,该语句将检查下一个数字是否为负数。

例如

long long product = 1;

//...

while ( fscanf( in, "%d", &x ) == 1 )
{
    if ( x < 0 )
    {
        printf( "%d ", x );
        product *= x;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    相关资源
    最近更新 更多