我想在用户输入“0”时结束程序,当我使用do / while循环时工作正常但是现在我不想在输出上出现“0”...我只是希望程序在用户输入0时结束,但不将其计为输出行
这是我的输入:(每行)
1.0
0.2
10.0
20.0
0
以下是我的代码的主要部分:
main()
{
float* fArray;
float value;
int counter = 0;
int i;
do
{
scanf("%f", &value);
*(fArray + counter) = value;
counter++;
}
while (value != 0);
printf("\nThe original values are: ");
for (i = 0; i < counter; i++)
printf("%g ", *(fArray + i));
}
答案 0 :(得分:3)
do
{
scanf("%f", &value);
if (value != 0)
{
*(fArray + counter) = value;
counter++;
}
}
while (value != 0);
答案 1 :(得分:2)
你应该做的一些事情:我编辑并注释你的代码
#include <stdio.h> // for I/O
#include <stdlib.h> // for malloc
//main()
int main(void) { // get the signature of main() right
float* fArray;
float value = -1;
int N_MAX=100; // decide on largest number of entries you will allow
int counter = 0;
int i;
// allocate memory for the array!
if((fArray = malloc(N_MAX * sizeof *fArray))==NULL) { // <<< and check that it worked
fprintf(stderr, "error allocating memory\n");
return -1;
}
do
{
// scan, and test for valid input:
if(0 == scanf("%f", &value)) break; // test that a float was read
if (value==0) {
break; // 0 = "end of input"
}
*(fArray + counter++) = value; // we only increment counter if valid value read
if(counter >= N_MAX) { // <<< don't run past the end of the array
fprintf(stderr, "maximum number of entries reached\n");
break;
}
}
while (1==1); // "infinite" loop - we break internally when break condition is met
// taking the next line out: moving some of the functionality into the loop
// to correct the logic as pointed out in the comments
// counter--; // undo the "one too far" count
printf("\ntotal number of good values: %d\n", counter);
printf("The original values are: ");
for (i = 0; i < counter; i++) { // <<<< good habit to use {} even for a one liner
printf("%g ", *(fArray + i));
}
printf("\n"); // <<< don't want to end without CRLF - or prompt will be at end of line
}
答案 2 :(得分:1)
您需要分配一些内存来放置值。
即。
float fArray[1000]; // Some large enough number here
然后使用
scanf("%f", &value)); // Hopefully you get the picture and also you should check the return value
fArray[counter++] = value;
这也会增加索引counter
答案 3 :(得分:1)
for (i = 0; i < counter-1; i++)
printf("%g ", *(fArray + i));
答案 4 :(得分:1)
我认为,你可以使用if语句来打印&#34; 0&#34;在输出语句中,如
for(i=0;i<counter;i++)
{if(*(fArray + i)==0)
{}
else{
printf("%g ", *(fArray + i));
}
}
答案 5 :(得分:0)
main() {
float* fArray;
float value;
int counter = 0;
int i;
fArray = (float *) malloc(sizeof(float)*100);
while(1){
scanf("%f", &value);
if(value == 0) {
break;
}
*(fArray + counter ) = value;
counter++;
}
printf("\nThe original values are: ");
for (i = 0; i < counter; i++)
printf("%g ", *(fArray + i));
}